标签:
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时是空
自己挖的坑自己填...
纯属自己作,希望能有老司机指点其他解决方法
FragmentPagerAdapter加载fragment并使用setUserVisibleHint()处理预加载时遇到的坑,给textview赋值时出现的空指针异常
标签:
原文地址:http://www.cnblogs.com/Jieth/p/5855757.html