【问题标题】:android- how to use ViewModelProviders in custom dialog classandroid-如何在自定义对话框类中使用 ViewModelProviders
【发布时间】:2020-02-08 06:27:53
【问题描述】:

我有一个自定义对话框类,这是我的代码:

class DialogBimegozar_new(act: Activity){
private var dialog: Dialog
private var act: Activity
private lateinit var viewModel:BimeGozarViewModel

init {
    dialog = Dialog(act, R.style.DialogStyler);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.dialog_bimegozar_new)

    this.act = act

    makeDialog()

    val lp = WindowManager.LayoutParams()
    lp.copyFrom(dialog.window?.attributes)
    lp.width = WindowManager.LayoutParams.MATCH_PARENT
    lp.height = WindowManager.LayoutParams.MATCH_PARENT
    dialog.getWindow()?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
    dialog.window?.attributes = lp

    dialog.show()
}

private fun makeDialog() {
    viewModel=ViewModelProviders.of(act)

}

我想在课堂上使用我的视图模型,我在这行有一个错误:

viewModel=ViewModelProviders.of(act)

错误是: 可以使用提供的参数调用以下选项中的非选项 的(片段)定义... (fragmentActivity) 的定义......

在上面的代码中行动是我的活动 问题是什么 ?我可以在自定义类中使用视图模型吗?

【问题讨论】:

    标签: android android-dialog android-viewmodel


    【解决方案1】:

    您可以实现自己的 ViewModelFactory 或使用 sdk 提供的工厂并创建 ViewModel 的实例。喜欢:

    final ViewModelProvider.NewInstanceFactory factory = new ViewModelProvider.NewInstanceFactory();
    YourViewModel viewModel = factory.create(YourViewModel.class);
    

    或者如果您的 ViewModel 类扩展了 AndroidViewModel:

    final ViewModelProvider.AndroidViewModelFactory androidFactory = new ViewModelProvider.AndroidViewModelFactory(((Application) context.getApplicationContext()));
    YourViewModel viewModel = androidFactory.create(YourViewModel.class);
    

    【讨论】:

      猜你喜欢
      • 2014-07-29
      • 2020-04-10
      • 2017-02-22
      • 2016-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多