一个Fragment基类,两个Fragment分别去继承它,当切换到第二个Fragment的时候提示找不到布局的控件了,那应该是没有绑定上,我这种情况应该怎么改?
下面是三个类和报错截图
public abstract class LazyFragment extends Fragment {
private Unbinder mUnbinder;
private boolean isLoaded; //标志位,判断是否已经加载过该界面,保证只加载一次
private View mContainerView;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//可见了但是没初始化
if (getUserVisibleHint() && !isLoaded) {
mContainerView = inflater.inflate(contentViewId(), container, false);
isLoaded = true;
} else {
//不可见,加载其他布局
mContainerView = inflater.inflate(R.layout.lazy_loading, container, false);
mContainerView.setBackgroundColor(lazyFragmentBackground());
}
return mContainerView;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mUnbinder = ButterKnife.bind(this, view);
initView(savedInstanceState, view);
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && !isLoaded) {
if (mContainerView instanceof ViewGroup) { //是不是viewgroup,然后移除那些简单view,加载重布局
ViewGroup group = ((ViewGroup) mContainerView);
group.removeAllViews();
View view = LayoutInflater.from(getActivity()).inflate(contentViewId(), group, false);
group.addView(view);
super.onViewCreated(mContainerView, null);
lazyLoad();
isLoaded = true;
}
}
}
protected int lazyFragmentBackground() {
return ContextCompat.getColor(getActivity(), R.color.lazy_fragment_background);
}
protected abstract void lazyLoad();
public abstract void initView(Bundle savedInstanceState, View view);
public abstract int contentViewId();
@Override
public void onDestroy() {
super.onDestroy();
if (mUnbinder != null) {
mUnbinder.unbind();
mUnbinder = null;
}
}
}
public class OneFragment extends LazyFragment {
@BindView(R.id.tv_one)
TextView mTextView;
private static final String TAG = "OneFragment";
@Override
public int contentViewId() {
Log.d(TAG, "5678contentViewId: 11111111111111");
return R.layout.fragment_one;
}
@Override
public void initView(Bundle savedInstanceState, View view) {
Log.d(TAG, "5678initView: 11111111111111");
mTextView.setText("aaaaaaaaaaaaa");
}
@Override
protected void lazyLoad() {
Log.d(TAG, "5678setUserVisibleHint: 可见111111111111");
}
}
public class TwoFragment extends LazyFragment {
@BindView(R.id.tv_two)
TextView mTextView;
private static final String TAG = "TwoFragment";
@Override
public int contentViewId() {
Log.d(TAG, "5678contentViewId: 22222222222222222");
return R.layout.fragment_two;
}
@Override
public void initView(Bundle savedInstanceState, View view) {
Log.d(TAG, "5678initView: 2222222222222222");
mTextView.setText("bbbbbbbbbbbbbb");
}
@Override
protected void lazyLoad() {
Log.d(TAG, "5678setUserVisibleHint: 可见2222222222222");
}
}