Android 片段 onAttach() 已弃用 [英] Android Fragment onAttach() deprecated

查看:38
本文介绍了Android 片段 onAttach() 已弃用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已更新我的应用以使用最新的支持库(版本 23.0.0),我发现他们弃用了 Fragment 类的 onAttach() 函数.

I have updated my app to use the latest support library (version 23.0.0), I've found out that they deprecated the onAttach() function of the Fragment class.

代替:

onAttach (Activity activity)

现在:

onAttach (Context context)

由于我的应用程序使用在弃用之前通过的活动,我认为可能的解决方案是:

As my app uses the activity passed before deprecation, a possible solution i think is:

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    activity = getActivity();
}

这是正确的做法吗?

更新:

如果我运行 API 低于 23 的设备,则甚至不会调用新的 onAttach().我希望这不是他们想要做的!

If i run a device with API lower than 23, the new onAttach() is not even being called. I hope that this is not what they intended to do!

更新 2:

问题已通过 SDK 的最新更新得到解决.

Issue has been resolved with the latest updates to the SDK.

我已经在我的 API 22 设备上进行了测试,并且正在调用 onAttach(Context).

I have tested on my API 22 device and onAttach(Context) is being called.

点击此处关注我的错误报告几周前开业,以及来自 Google 员工的回答.

Click here to follow the bug report I've opened a couple of weeks ago and the answers from the guys at Google.

推荐答案

Activity 是一个上下文,所以如果你可以简单地检查上下文是一个 Activity 并在必要时转换它.

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;
    }

}

更新:有些人声称新的 Context 覆盖从未被调用.我做了一些测试,但找不到这样的场景,根据源代码,它永远不应该是真的.在我测试的所有情况下,无论是在 SDK23 之前还是之后,ActivityContext 版本的 onAttach 都被调用.如果您能找到不是这种情况的场景,我建议您创建一个示例项目来说明问题和 报告给 Android 团队.

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.

更新 2:我只使用 Android 支持库片段,因为那里的错误修复得更快.似乎只有在您使用框架片段时才会发现上述无法正确调用覆盖的问题.

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.

这篇关于Android 片段 onAttach() 已弃用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆