|
|
@@ -7,8 +7,30 @@ import androidx.lifecycle.MutableLiveData;
|
|
|
import androidx.lifecycle.ViewModel;
|
|
|
|
|
|
/**
|
|
|
- * 使用ViewModel保存Fragment的数据,阻止Fragment在配合BottomNavigationView切换时总被销毁的问题
|
|
|
+ * 使用ViewModel + LiveData保存Fragment的数据,阻止Fragment在配合BottomNavigationView切换时总被销毁的问题
|
|
|
+ *
|
|
|
*/
|
|
|
+/*public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
|
|
|
+ mainViewModel=new ViewModelProvider(getActivity()).get(MainViewModel.class);
|
|
|
+ root=mainViewModel.getHomeView().getValue();
|
|
|
+ if(root==null){
|
|
|
+ //正常初始化View
|
|
|
+ root = inflater.inflate(R.layout.fragment_home, container, false);
|
|
|
+ //...
|
|
|
+ }
|
|
|
+ //...
|
|
|
+ return root;
|
|
|
+}*/
|
|
|
+/*@Override
|
|
|
+public void onDestroyView() {
|
|
|
+ super.onDestroyView();
|
|
|
+ //其实以下代码不一定写在onDestroyView(),可以获取指定后root的地方都可以
|
|
|
+ ViewGroup parent = (ViewGroup) root.getParent();
|
|
|
+ if(parent!=null){
|
|
|
+ parent.removeView(root);
|
|
|
+ }
|
|
|
+ mainViewModel.setHomeView(root);
|
|
|
+}*/
|
|
|
public class MainViewModel extends ViewModel {
|
|
|
private MutableLiveData<View> mTemplateView;
|
|
|
private MutableLiveData<View> mHomeView;
|