Kotin 将参数从片段传递给 ViewModel

问题描述 投票:0回答:1

我使用 MVVM 和分页都工作正常,但是当我将参数传递给 viewModel 时,应用程序崩溃了错误

使用过的回收适配器代码

    val modelViewModel = ViewModelProvider(this).get(ModelsViewModel(30).javaClass)
    val modelsAdapter = ModelsAdapter(this,requireContext())
    modelViewModel.modelsPageList.observe(viewLifecycleOwner, Observer { models->
        modelsAdapter.submitList(models)
        model_recycle.also {
            it.layoutManager = LinearLayoutManager(requireContext())
            it.setHasFixedSize(true)
            it.adapter = modelsAdapter
        }
    })

modelView类在这里命名为ModelsViewModel

class ModelsViewModel(args:Int) : ViewModel() {
    private var liveDataSource: MutableLiveData<PageKeyedDataSource<Int,ModelsData>>
    var modelsPageList:LiveData<PagedList<ModelsData>>

    init {
        val modelsDataSourceFactory = ModelsDataSourceFactory(args)
        liveDataSource = modelsDataSourceFactory.getModelsLiveDataSource()
        val config = PagedList.Config.Builder()
            .setEnablePlaceholders(false)
            .setPageSize(ModelsDataSource(args).PAGE_SIZE)
            .build()
        modelsPageList = LivePagedListBuilder<Int,ModelsData>(modelsDataSourceFactory, config).build()
    }
}

dataSourceFactory 的类名为 ModelsDataSourceFactory

class ModelsDataSourceFactory(private val args:Int): DataSource.Factory<Int,ModelsData>() {

    private var modelLiveDataSource:MutableLiveData<PageKeyedDataSource<Int,ModelsData>> = MutableLiveData()

    override fun create(): DataSource<Int, ModelsData> {
        val modelDataSource = ModelsDataSource(args)
        modelLiveDataSource.postValue(modelDataSource)
        return modelDataSource
    }

    fun getModelsLiveDataSource():MutableLiveData<PageKeyedDataSource<Int,ModelsData>>{
        return modelLiveDataSource
    }
} 

最后一个名为 ModelsDataSource 的类数据源

class ModelsDataSource(args:Int): PageKeyedDataSource<Int, ModelsData>() {
...
}

我尝试为 modelView 进行第二个构造,也导致应用程序崩溃

android kotlin mvvm
1个回答
0
投票

为您的视图模型创建一个工厂类:

 public class ModelsViewModelFactory implements ViewModelProvider.Factory {
    private int args;


    public ModelsViewModelFactory(int args) {       
        this.args = args;
    }

    @Override
    public <T extends ViewModel> T create(Class<T> modelClass) {
        return (T) new ModelsViewModel(args);
    }
}

实例化视图模型时,请这样做:

ModelsViewModelFactory factory = new ModelsViewModelFactory(30);    
ModelsViewModel modelViewModel = ViewModelProvider(this,factory).get(ModelsViewModel.class);

希望这能让您了解如何将参数传递给视图模型。

© www.soinside.com 2019 - 2024. All rights reserved.