FragmentPagerAdapter加载fragment并使用setUserVisibleHint()处理预加载时,给textview赋值时出现的空指针异常
public class BaseFragment extends Fragment {
/*布局*/
private View view;
/**/
boolean isVisible = false;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = setRootView(inflater,container);
Log.i("包名:"+getClass().getName(),"onCreateView");
return view;
}
protected View setRootView(LayoutInflater inflater, @Nullable ViewGroup container){
return null;
}
protected void initWidght(){};
protected void initData(){};
/**
* 解决预加载
* */
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
Log.i("包名:"+getClass().getName()," setUserVisibleHint 显示"+getUserVisibleHint());
if (getUserVisibleHint()){
onVisible();
isVisible = true;
}else {
// onInvisible();
}
}
/**
* 预加载--显示-加载数据
* */
private void onVisible() {
if (!isVisible){
initWidght();
}
}
/**
* 预加载--不显示时
* */
private void onInvisible() {
isVisible = false;
}
protected <T extends View>T getView(int resourcesId){
return (T) view.findViewById(resourcesId);
}
/**
* Toast提示;
* @param content 提示内容;
*/
protected void showToast(String content) {
Toast.makeText(getActivity(), content, Toast.LENGTH_SHORT).show();
}
}
public class IndexChatFragment extends BaseFragment {
TextView mTextView;
@Override
protected View setRootView(LayoutInflater inflater, @Nullable ViewGroup container) {
return inflater.inflate(R.layout.fragment_index_chat,container,false);
}
@Override
protected void initWidght() {
mTextView = getView(R.id.ceshi);
mTextView.setText("赋值测试");
}
出现了这个错误
测试发现具体问题是:只有加载的第一个Fragment会出现这种状况,后边则可以正常显示
最后打印了生命周期才发现是这样的,setUserVisibleHint是比oncreateView先加载,所以第一个调用setUserVisibleHint时是空
onCreateView和setUserVisibleHint都调用onvisible(),两个条件同事满足则加载布局或者数据
view也可以单独换成一个标记,在oncreateView里赋值true
|