onAttach(Context)在API23不响应解决方法

  在fragment向activity传值时需要使用onAttach方法,由于onAttach(activity,Activity):void已被弃用,只能用onAttach(contex,Contex):void,但是在API<23时并不会去调用此方法,即会导致程序崩溃(此为google一个bug)。

  解决方法有3个:

1.Using getSupportFragmentManager() will force you to use a Fragment from the support lib. So the first solution is to replace all fragments with the fragment from support lib and using getSupportFragmentManager().

  使用 getSupportFragmentManager() 会强行使用该 support lib 里的Fragment, 所以通过使用getSupportFragmentManager()把所有原Fragment都替换成support lib 里的Fragment.

2.Solution that I've already implemented is to handle 2 possibilities

“我”已经亲测能处理这两种情况(应用是在API<23下运行或在API>=23下运行(Ps:这不是所有API下吗)。in my implementation I have a base class for all fragments from the project and I added this code there在我的实现办法中我在项目中为所有的frament建立了一个基础类,这里上码:

/*
 * onAttach(Context) is not called on pre API 23 versions of Android and onAttach(Activity) is deprecated
 * Use onAttachToContext instead
 */
@TargetApi(23)
@Override
public void onAttach(Context context) {
    super.onAttach(context);
    onAttachToContext(context);
}

/*
 * Deprecated on API 23
 * Use onAttachToContext instead
 */
@SuppressWarnings("deprecation")
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        onAttachToContext(activity);
    }
}

/*
 * Called when the fragment attaches to the context
 */
protected void onAttachToContext(Context context) {
}

以上为国际友人@David Rauca提供解答,本鸟粗略翻译,并且以上2个方法我没有亲测(或是没成功),对于我这种小白来说感觉复杂了点,所以出现了第三个方法:
3.After I read your answer @David Rauca I think the second one can solve my problem. But when I look into the source code. I found that actually, onAttach(Context context) do nothing on Android M, just called the old method.---- Tony Zhang
  重点:我发现事实上你娃说的第二种办法在Android M上没卵用,我就强行用老办法了~
@SuppressWarnings("deprecation")
在onAttach(activity,Activity):void上加上此申明便可任性使用,亲测完美解决本鸟的程序崩溃。感谢两位答主。

 

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值