创建自定义参数android viewmodel类

时间:2018-06-30 12:26:55

标签: android kotlin viewmodel

这将创建具有默认或零参数的MyViewModel对象。

MyActivity

ViewModelProviders.of(this)
                .get(MyViewModel::class.java)

如果MyViewModel类具有自定义参数构造函数,如何创建?

MyViewModel

class MyViewModel(context: Application,
                        private val repository: MistakesRepository) : AndroidViewModel(context) {


    val showLoading = ObservableBoolean(false)
    val liveItems = MutableLiveData<List<Mistake>>()

    fun loadAllMistakes(forceLoad: Boolean) {

    }

}

在搜索了几篇博客文章之后,可以通过具有自定义工厂对象来完成。但是,为什么没有有关此开发人员页面的文档?还是我错过了这里的东西?

2 个答案:

答案 0 :(得分:3)

ViewModelProviders.of(this, object : ViewModelProvider.Factory {
            override fun <T : ViewModel?> create(modelClass: Class<T>): T {
                @Suppress("UNCHECKED_CAST")
                return MyViewModel(applicationContext, mistakesRepository) as T
            }
        })[MyViewModel::class.java]

答案 1 :(得分:1)

我可以在JAVA中为您提供帮助。希望你能比我更好地转换为kotlin。

class MyViewModelFactory implements ViewModelProvider.Factory {

    private final Context context;
    private final MistakesRepository repository;

    @Inject
    public MyViewModelFactory(Context context, MistakesRepository repository) {
       this.context = context;
       this.repository = repository;
    }

    @Override
    public MyViewModel create(Class modelClass) {
        return new MyViewModel(context, repository);
    }
}

然后最后使用:

@Inject MyViewModelFactory factory;
...
MyViewModel createViewModel() {
    return ViewModelProviders.of(this,factory)
                             .get(MyViewModel.class);
}

尝试科特林

class MyViewModelFactory @Inject constructor(val context: Context, val repository: MistakesRepository) : ViewModelProvider.Factory {

        override fun create(modelClass: Class): MyViewModel {
            return MyViewModel(context, repository);
        }
    }

@Inject lateinit var factory : MyViewModelFactory
...
fun createViewModel() : MyViewModel {
    return ViewModelProviders.of(this,factory)
                             .get(MyViewModel::java.class);
}