如何使用 Factory 将自定义参数传递给 ViewModel?

我知道为了将自定义参数传递给ViewModel,我们可以使用ViewModelProvider.NewInstanceFactory,像这样:


// Factory Class    

class MyFactory extends ViewModelProvider.NewInstanceFactory {


        private final String mId;

        public MyFactory(String id) {

            mId = id;

        }


        @NonNull

        @Override

        public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {

            return (T) new MyViewModel(mId);

        }

    }



// MyViewModel class

class MyViewModel extends ViewModel {


  public MyViewModel(String id) {

     ...

  }

}


// Activity I can Initialise as: 

MyFactory modelFactory = new MyFactory(id);

viewModel = ViewModelProviders.of(this, modelFactory).get(MyViewModel.class);

如何使用AndroidViewModel子类中的自定义参数以及应用程序上下文实现相同的效果。喜欢


// MyAndroidViewModel class

    class MyAndroidViewModel extends AndroidViewModel {


      public MyViewModel(Application context, String id) {

         super(context);

         ...

      }

    }

如何初始化MyAndroidViewModel以及ViewModelProvider.NewInstanceFactory如何在这里发挥作用?


慕尼黑5688855
浏览 201回答 1
1回答

侃侃无极

我以前遇到过这个问题,我通过这样做来解决它。在您的活动中,创建您的ViewModel工厂,如下所示://Inside MyActivityViewModelProvider.Factory factory = new ViewModelProvider.Factory() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @NonNull&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return (T) new MyAndroidViewModel(getApplication(),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "My string!");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; };然后用它来创建你的ViewModel:viewModel = ViewModelProviders.of(this, factory).get(MyAndroidViewModel.class);&nbsp;更新:由于ViewModelProviders该类已被弃用,更新后的答案如下。工厂和以前一样,只是换成了 Kotlin。var factory = object : ViewModelProvider.Factory {&nbsp; &nbsp; &nbsp; &nbsp; override fun <T : ViewModel?> create(modelClass: Class<T>): T {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; SimpleAndroidViewModel(activity!!.application,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "My string!") as T&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }但是,我们创建 ViewModel 实例的行已经改变,现在我们正在使用ViewModelProvider该类。private val viewModel: SimpleAndroidViewModel by lazy {&nbsp; &nbsp; &nbsp; &nbsp; ViewModelProvider(this, factory).get(SimpleAndroidViewModel::class.java)&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java