片段setuserVisibleHint true,但getActivity返回null [英] Fragment setuserVisibleHint true but getActivity returns null

查看:159
本文介绍了片段setuserVisibleHint true,但getActivity返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在片段的 setUserVisibleHint()方法中执行一些逻辑。我总是检查 isVisibleToUser 是否为true,然后使用 getActivity 返回活动。在我将支持库更新到最新版本( support:appcompat-v7:24.2.0 )之前,这一切都运行良好(100%的时间)。现在 getActivity 总是返回null。是否有支持库的一些更改解释这种行为?

  @Override 
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(false);

if(isVisibleToUser){
getActivity()< - null
}

$ b $根据Google的说法:在Android N之前,有一个平台错误可能会导致setUserVisibleHint在其FragmentTransaction被破解之前将一个片段带到启动状态由于某些应用程序依赖于此行为,因此它会保留用于声明targetSdkVersion为23或更低的应用程序。



因此,有两种选择:
1.用targetSdkVersion重建< 24;
2.根据新情况修改应用程序=>分别在onAttach方法中或在分段生命周期中稍后使用此回调之外的上下文;


I've been doing some logic inside of a fragment's setUserVisibleHint() method. I was always checking if isVisibleToUser is true and then used getActivity to return the activity. This was working well (100% of the time) until I updated the support library to the latest(support:appcompat-v7:24.2.0). Now getActivity always returns null. Are there some changes to the support library that explain this behaviour?

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(false);

    if (isVisibleToUser) {
      getActivity() <- null
    }

解决方案

According to Google: "Prior to Android N there was a platform bug that could cause setUserVisibleHint to bring a fragment up to the started state before its FragmentTransaction had been committed. As some apps relied on this behavior, it is preserved for apps that declare a targetSdkVersion of 23 or lower."

So, there are two options: 1. rebuild with targetSdkVersion < 24; 2. modify the app according to new situation => use the context outside this callback, respectively in onAttach method or later on in the fragment lifecycle;

这篇关于片段setuserVisibleHint true,但getActivity返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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