Android ViewModel recreated on screen rotation

前端 未结 4 1142
滥情空心
滥情空心 2021-02-14 11:01

I found a case when architecture components ViewModel isn\'t retained - in short it goes as follows:

  1. Activity is started and ViewModel in
4条回答
  •  春和景丽
    2021-02-14 11:27

    For others that may not be helped by previous answers like me, the problem could be that you haven't set up your ViewModelProvider properly with a factory.

    After digging around I solved my similiar problem by adding the following method to my Activities:

    protected final  ViewModel obtainViewModel(@NonNull AppCompatActivity activity, @NonNull Class modelClass) {
        ViewModelProvider.AndroidViewModelFactory factory = ViewModelProvider.AndroidViewModelFactory.getInstance(activity.getApplication());
        return new ViewModelProvider(activity, factory).get(modelClass);
    }
    

    And then I did this in my Fragments:

    protected final  ViewModel obtainFragmentViewModel(@NonNull FragmentActivity fragment, @NonNull Class modelClass) {
        ViewModelProvider.AndroidViewModelFactory factory = ViewModelProvider.AndroidViewModelFactory.getInstance(fragment.getApplication());
        return new ViewModelProvider(fragment, factory).get(modelClass);
    }
    

    I already had some abstract super classes for menu purposes so I hid the methods away there so I don't have to repeat it in every activity. That's why they are protected. I believe they could be private if you put them in every activity or fragment that you need them in.

    To be as clear as possible I would then call the methods to assign my view model in onCreate() in my activity and it would look something like this

    private MyViewModel myViewModel;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myViewModel = (MyViewModel) obtainViewModel(this, MyViewModel.class);
    }
    

    or in fragment

    private MyViewModel myViewModel;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getActivity() != null) {
            myViewModel = (MyViewModel) obtainFragmentViewModel(getActivity(), MyViewModel.class);
        }
    }
    

    It seems to work fine so far. If someone have a better way please let us know!

提交回复
热议问题