Fragment的onAttach(Context)没有被调用

来源:互联网 发布:linux桌面安装包 编辑:程序博客网 时间:2024/04/28 23:43

问题描述:

在使用API 23进行app开发时发现,Fragment类的onAttach(Activity)方法被标识为deprecated,也就是说该方法不推荐被继续使用,换成推荐的onAttach(Context)
可是当app在设备(Android 5.1.1)上运行时,代替的onAttach(Context)并没有被调用。

问题分析:

If you run the application on a device with API 23 (I’ve run it on the AS Emulator), you’ll see that the onAttach(Context) method will be called. During the process for showing a fragment by the FragmentManager, at a specific moment the onAttach(..) method is called.
Using the getFragmentManager() you’ll get an instance of the fragment manager available for the Android version which is running on that device (for example API 22, 23). In case the application is running on a device with API < 23 the onAttach(Context) method is not available, the fragment manager doesn’t know that in API 23 there is a method onAttach(Context), so that’s why it is not called for the API < 23 -> the solution for this kind of problems is using the FragmentManager from support libraries.

从stackoverflow找到相似问题的原因:
当你的app在API 23的设备上运行的时候,你会发现onAttach(Context)确实是会被调用的。调用getFragmentManager()方法,你会获得一个设备当前android版本的Fragment Manager,也就是API 23。
可是当你的app运行在API < 23的设备时,问题就来了。当你调用getFragmentManager()方法时,你获得的Fragment Manager的版本也是小于23的,这时候的获得的Fragment Manager是不知道API 23会有一个onAttach(Context)方法的,所以依旧会调用onAttach(Activity)方法,而不会调用onAttach(Context)方法。

解决方案:

重写两个onAttach()方法,处理在API 23以下和API 23以上两种设备运行的情况。

@Overridepublic void onAttach(Context context) {    super.onAttach(context);    // Code here}/*SDK API<23时,onAttach(Context)不执行,需要使用onAttach(Activity)。Fragment自身的Bug,v4的没有此问题*/@SuppressWarnings("deprecation")@Overridepublic void onAttach(Activity activity) {    super.onAttach(activity);    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {        // Code here    }}

参考:
http://stackoverflow.com/questions/32083053/android-fragment-onattach-deprecated
http://stackoverflow.com/questions/32077086/android-onattachcontext-not-called-for-api-23/32268249#32268249

0 0