在setUserVisibleHint方法中应使用什么上下文 [英] What context Should be Use in setUserVisibleHint Method

查看:83
本文介绍了在setUserVisibleHint方法中应使用什么上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为所有片段一起加载,所以在"Pager滑动"选项卡中,我需要使用setUserVisibleHint()对选定的片段进行处理. 我在setUserVisibleHint()方法中遇到上下文问题: 当我在上下文中使用getActivity时,它引发了NPE Exception.谢谢

Because All fragment loaded with together In Pager Sliding tab , I need to use setUserVisibleHint() for laoding that fragment selected . I have Problem with Context in the setUserVisibleHint() method : It raised NPE Exception when I use getActivity for my Context. Thanks

推荐答案

由于 getActivity 在片段附加到活动之前将返回null,因此您需要检查此值是否为null或检查附加到活动中或在 onActivityActtached 函数之后的片段.

Because getActivity will return null before fragment attached to Activity you need check this value will null or check fragment attached to activity or after onActivityActtached function.

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (getActivity() != null) {
       //do something
    }
} 

//or 
 boolean isAttached = false;
 @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        isAttached = true;
    }

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isAttached) {
       //do something
    }
} 

这篇关于在setUserVisibleHint方法中应使用什么上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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