I have a LoginActivity which extends AccountAuthenticatorActivity. This activity has several fragments which are androidx.fragment.app.Fragments. The Problem is from fragments I can't call:
((LoginActivity) getActivity()).setAccountAuthenticatorResult(intent.getExtras());
Because LoginActivity extends AccountAuthenticatorActivity which extends android.app.activity but getActivity() returns androidx.fragment.app.FragmentActivity which can't be cast to my LoginActivity. If I use android.app.Fragment I can't use methods like getViewLifecycleOwner() of androidx Fragment. So what's the solution here?
Update:
Although delegation pattern could solve this problem, this question has an interesting answer here:
AccountAuthenticatorActivity and fragments
I think one solution is delegation pattern. It is a technique where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behavior to an associated object. For implementation of delegation pattern you should use an interface like this:
public interface Delegate extends Serializable {
void setResult(Intent intent);
}
then AccountAuthenticatorActivity should implements this interface and inside setResult call the method.
public void setResult(Intent intent){
setAccountAuthenticatorResult(intent.getExtras());
}
your Fragment class should be like this:
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;
}
I accepted the delegation pattern answer, but I've still had the problem with androidx fragments in AccountAuthenticatorActivity. I think I should've used same pattern with AppCompatDelegate. For anyone facing the same issue I suggest this answer: AccountAuthenticatorActivity and fragments
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With