问题描述
因为所有片段一起加载,所以在"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方法中应使用什么上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!