问题描述
我正在使用 ViewPager
并使用碎片
,我发现
setUserVisibleHint()在片段中的onCreateView()之前调用
我使用片段
从支持库 android.support.v4.app.Fragment
这是库的问题吗?
如何摆脱它?
> EDIT
我覆盖setUserVisibleHint(),不调用super来摆脱它。
<$在片段中的onCreateView()之前调用导致NullPointerException的pre>
@Override
public void setUserVisibleHint(boolean isVisibleToUser){
// FIXED:setUserVisibleHint super.setUserVisibleHint(isVisibleToUser);
}
//为获取数据创建布尔值
private boolean isViewShown = false;
@Override
public void setUserVisibleHint(boolean isVisibleToUser){
super.setUserVisibleHint(isVisibleToUser);
if(getView()!= null){
isViewShown = true;
// fetchdata()包含当页面被选择时显示数据的逻辑主要asynctask填充数据
fetchData();
} else {
isViewShown = false;
}
}
使用 isViewShown
实例变量来决定是否在中获取数据onCreateView()
或在 setUserVisibleHint()
p>
以下代码包含的逻辑onCreateView()
:
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,
Bundle savedInstanceState){
View view = inflater.inflate(R.layout.main_layout,容器,假);
//查看初始化步骤.......
if(!isViewShown){
fetchData();
}
//做其他东西
}
会解决你的问题。因为它解决了我的问题。 :)
这个技巧将从 onCreateView()
中获取数据以直接从一个页面跳转到另一个页面,你刷过视图,它会从 setUserVisibleHint()
方法中获取数据。 :)
I am working on ViewPager
and using Fragment
there I found
I am using Fragment
from support library android.support.v4.app.Fragment
Is this is a problem with Library ?
How can I get rid of it ?
EDIT
I Override setUserVisibleHint() and not calling super to get rid of it.
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
//FIXED: setUserVisibleHint() called before onCreateView() in Fragment causes NullPointerException
//super.setUserVisibleHint(isVisibleToUser);
}
// create boolean for fetching data
private boolean isViewShown = false;
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (getView() != null) {
isViewShown = true;
// fetchdata() contains logic to show data when page is selected mostly asynctask to fill the data
fetchData();
} else {
isViewShown = false;
}
}
Use isViewShown
instance variable to decide whether to fetch data in onCreateView()
or in setUserVisibleHint()
.
Below code contains logic for onCreateView()
:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_layout, container, false);
// view initialization steps.......
if (!isViewShown) {
fetchData();
}
// do other stuff
}
This code will solve your problem. As It solved my problem. :)
This trick will fetch data in onCreateView()
for direct jumping from one page to another, whereas when you swipe the view it will fetch the data from setUserVisibleHint()
method. :)
这篇关于setUserVisibleHint在Fragment中的onCreateView之前调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!