fragment原来的页面切换被重新实例化,无法继续保持上一次的内容。只让它执行一次

最好的方法是:
定义类.静态变量的方式 保存数据,从这里取。
用网上其他人的方法,fragment切换速度太快会报错 child view 没有从parent view 中移除;

               只执行一次,定义一个flag就行了,用 类.静态变量判断;


      if (fragmentState.fragmentone){
        new client(this);
        fragmentState.fragmentone=false;
        }

我的做法是只让它执行一次就行了,视图重新加载没有问题,加载完后再接上数据;

参考:

public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// if(fragmentState.homefragment_rootView==null){
//
// // fragmentState.homefragment_floatActionButton = fragmentState.homefragment_rootView.findViewById(R.id.floatingActionButton_Add);
//
//// fragmentState.homefragment_floatActionButton.setOnClickListener(new View.OnClickListener() {
//// @Override
//// public void onClick(View view) {
//// Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//// .setAction("Action", null).show();
//// }
//// });
// }
fragmentState.homefragment_rootView = inflater.inflate(R.layout.fragment_home, container, false);
fragmentState.homefragment_buttonGridView = fragmentState.homefragment_rootView.findViewById(R.id.buttonGridview);
fragmentState.homeframent_textView = fragmentState.homefragment_rootView.findViewById(R.id.textView);
fragmentState.homeframent_textView.setText(HomeViewModel.revJsonString);
//缓存的rootView需要判断是否已经被加过parent, 如果有parent需要从parent删除,要不然会发生这个rootview已经有parent的错误。
// ViewGroup parent = (ViewGroup) fragmentState.homefragment_rootView.getParent();
// if (parent != null) {
// parent.removeView(fragmentState.homefragment_rootView);
// }

    if (fragmentState.fragmentone){
        new client(this);
        fragmentState.fragmentone=false;
    }

    return fragmentState.homefragment_rootView;

}

猜你喜欢

转载自www.cnblogs.com/zhaocundang/p/11976878.html