Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onAttach(Activity) deprecated: where I can check if the activity implements callback interface

Tags:

Before API 23 I used Fragment's onAttach methods to get my listener instance, then the reference is cleaned inside onDetach. ex:

@Override public void onAttach(Activity activity) {     super.onAttach(activity);     mListener = null;     try {         mListener = (SellFragmentListener) activity;     } catch (ClassCastException e) {         throw new ClassCastException(activity.toString()                 + " must implement SellFragmentListener");     } }  @Override public void onDetach() {     super.onDetach();     mListener = null; } 

Is it safe to do the same check inside onAttach(Context context) or is there a better way to get the holder activity instance?

like image 669
Ariel Carbonaro Avatar asked Aug 27 '15 19:08

Ariel Carbonaro


People also ask

What is onAttach in fragment in Android?

Below are the methods of fragment lifecycle. onAttach() :This method will be called first, even before onCreate(), letting us know that your fragment has been attached to an activity. You are passed the Activity that will host your fragment.

Is onAttach called before onCreate?

onAttach() is always called before any Lifecycle state changes. The onDetach() callback is invoked when the fragment has been removed from a FragmentManager and is detached from its host activity.

How do you use onAttach?

onAttach() : Called when a Fragment is first attached to a host Activity . Use this method to check if the Activity has implemented the required listener callback for the Fragment (if a listener interface was defined in the Fragment ). After this method, onCreate() is called.


1 Answers

Check the source code:

/**  * Called when a fragment is first attached to its context.  * {@link #onCreate(Bundle)} will be called after this.  */ public void onAttach(Context context) {     mCalled = true;     final Activity hostActivity = mHost == null ? null : mHost.getActivity();     if (hostActivity != null) {         mCalled = false;         onAttach(hostActivity);     } }  /**  * @deprecated Use {@link #onAttach(Context)} instead.  */ @Deprecated public void onAttach(Activity activity) {     mCalled = true; } 

So the onAttach(Activity activity) is called by the onAttach(Context context) if there is a host activity. You can use the onAttach(Activity activity) safely.

like image 125
Zsolt Mester Avatar answered Oct 04 '22 00:10

Zsolt Mester