Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is onAttach (Activity activity) deprecated?

After updating the SDK to API level 23, I found that onAttach (Activity activity) is deprecated and the new method is onAttach (Context context). can any one enlighten me on why this change was made?

like image 978
nvinayshetty Avatar asked Sep 04 '15 08:09

nvinayshetty


People also ask

What is onAttach in fragment?

onAttach(Activity) called once the fragment is associated with its activity. onCreate(Bundle) called to do initial creation of the fragment. onCreateView(LayoutInflater, ViewGroup, Bundle) creates and returns the view hierarchy associated with the fragment.

Is onAttach called before onCreateView?

Bookmark this question. Show activity on this post. In a Fragment's Lifecycle, the onAttach() method is called before the onCreate() method.

What is the fragment life cycle in Android?

Fragment life cycle is closely related to the life cycle of its host activity which means when the activity is paused, all the fragments available in the activity will also be stopped. A fragment can implement a behaviour that has no user interface component.


1 Answers

I think it has basically been to expand the scope of the method, but the official changelog doesn't say anything about it.

As you can see in the changelog they have removed the void onAttach(Activity) but they added a new one with the same name, and it says that is deprecated in the Android Official Documentation.

As richq commented, the support version of Fragment also deprecates onAttach(Activity) and has an onAttach(Context) that can be used instead on all Android versions right back to prehistoric ones.

To adapt to this new changes you can follow this steps:

  • Change the argument type of onAttach callback from Activity to Context. For unknown reason, this modification results in the fact that the method onAttach(Context) is not called anymore during the fragment lifecycle.

  • Move the code that was in onAttach method to onCreate one since it gets still executed.

With this modification, the app turns to run as before. No additional import statements are required.

like image 77
arodriguezdonaire Avatar answered Oct 22 '22 00:10

arodriguezdonaire