Fragment的onAttach(Context)没有被调用

本文探讨了在使用API23进行App开发时遇到的Fragment类中onAttach(Context)方法未被调用的问题。分析了该问题产生的原因,并提供了相应的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述:

在使用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以上两种设备运行的情况。

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

    // Code here
}

/*SDK API<23时,onAttach(Context)不执行,需要使用onAttach(Activity)。Fragment自身的Bug,v4的没有此问题*/
@SuppressWarnings("deprecation")
@Override
public 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值