将参数传递给AndroidViewModel并在活动和片段之间共享该ViewModel

时间:2019-11-15 07:57:25

标签: android-viewmodel

所以,我有一个活动,该活动通过工厂初始化viewmodel,以便它可以将自定义参数传递给viewmodel的构造函数。

public class MyActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout);

        Intent in = getIntent();
        if(in != null) {
           String source = in.getStringExtra(Constants.SOURCE);
           MyViewModel viewModel = new ViewModelProvider(this, new CustomViewModelFactory 
           (this.getApplication(), source)).get(MyViewModel.class);
        }      
    }
}
public class CustomViewModelFactory implements ViewModelProvider.Factory {
    private Application mApplication;
    private String mSource;

    public CustomViewModelFactory (Application application, String aSource) {
        mApplication = application;
        mSource = aSource;
    }

    @Override
    @NonNull
    @SuppressWarnings("unchecked")
    public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
        return (T) new MyViewModel(mApplication, mSource);
    }
}

现在,我想与片段共享该视图模型。片段下面的代码未返回由活动初始化的视图模型

viewModel = new ViewModelProvider(getActivity()).get(MyViewModel.class);

如何实现?

0 个答案:

没有答案