The onAttach() method has been deprecated in Android Fragment, so what is the alternative?

Asked 2 years ago, Updated 2 years ago, 128 views

I have just confirmed that onAttach() has been deprecated in the Fragment class since Android API 23. in the past onAttach (Activity activity) That's the part onAttach (Context context) It changed like this.

It changed like that

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    activity = getActivity();
}

Is this a good way?

android android-fragments

2022-09-22 22:25

1 Answers

Activity is included in Context. So if you just want to check if Context is an activity, you can cast and check.

@Override
public void onAttach(Context context) {
    super.onAttach(context);

    Activity a;

    if (context instanceof Activity){
        a=(Activity) context;
    }

}

Like this.


2022-09-22 22:25

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.