android activity 无法转换为 AccountAuthenticatorActivity

androidx activity can not be cast to AccountAuthenticatorActivity

我有一个扩展了 AccountAuthenticatorActivity 的 LoginActivity。这个 activity 有几个片段是 androidx.fragment.app.Fragments。问题来自我无法调用的片段:

((LoginActivity) getActivity()).setAccountAuthenticatorResult(intent.getExtras());

因为 LoginActivity 扩展了 AccountAuthenticatorActivity,后者扩展了 android.app.activity 但 getActivity() returns androidx.fragment.app.FragmentActivity 无法转换为我的 LoginActivity。如果我使用 android.app.Fragment 我不能使用像 androidx Fragment 的 getViewLifecycleOwner() 这样的方法。那么这里的解决方案是什么?

更新:

虽然委托模式可以解决这个问题,但这个问题在这里有一个有趣的答案:

AccountAuthenticatorActivity and fragments

请将整个项目迁移到androidx,如上截图

我认为一种解决方案是委托模式。它是一种对象向外部表达某些行为但实际上将实现该行为的责任委托给关联对象的技术。对于委托模式的实现,你应该使用这样的接口:

public interface Delegate extends Serializable {
    void setResult(Intent intent);
}

那么 AccountAuthenticatorActivity 应该实现这个接口并在 setResult 中调用该方法。

 public void setResult(Intent intent){
        setAccountAuthenticatorResult(intent.getExtras());
 }

你的片段class应该是这样的:

public  class MYFragment extends Fragment {

    Delegate delegate;

    public static MYFragment newInstance(Delegate delegate){
        MYFragment fragment = new MYFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("key", delegate);
        fragment.setArguments(bundle);
        return  fragment;
    }



    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup      container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.my_fragment,container,false);
        delegate = (Delegate) getArguments().getSerializable(<your_key>);
        delegate.setResult(<your_intent>);

        return view;
    }

我接受了委托模式的答案,但我仍然遇到 AccountAuthenticatorActivity 中的 androidx 片段问题。我想我应该对 AppCompatDelegate 使用相同的模式。对于面临同样问题的任何人,我建议这个答案:AccountAuthenticatorActivity and fragments