Android Fragment onAttach() deprecated
This is another great change from Google ... The suggested modification: replace onAttach(Activity activity)
with onAttach(Context context)
crashed my apps on older APIs since onAttach(Context context)
will not be called on native fragments.
I am using the native fragments (android.app.Fragment) so I had to do the following to make it work again on older APIs (< 23).
Here is what I did:
@Override
public void onAttach(Context context) {
super.onAttach(context);
// Code here
}
@SuppressWarnings("deprecation")
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
// Code here
}
}
Activity is a context so if you can simply check the context is an Activity and cast it if necessary.
@Override
public void onAttach(Context context) {
super.onAttach(context);
Activity a;
if (context instanceof Activity){
a=(Activity) context;
}
}
Update: Some are claiming that the new Context
override is never called. I have done some tests and cannot find a scenario where this is true and according to the source code, it should never be true. In all cases I tested, both pre and post SDK23, both the Activity
and the Context
versions of onAttach
were called. If you can find a scenario where this is not the case, I would suggest you create a sample project illustrating the issue and report it to the Android team.
Update 2: I only ever use the Android Support Library fragments as bugs get fixed faster there. It seems the above issue where the overrides do not get called correctly only comes to light if you use the framework fragments.