Kotin从片段向ViewModel传递参数

时间:2020-07-02 08:42:35

标签: android mvvm

我使用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也构造第二个应用程序

1 个答案:

答案 0 :(得分: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);

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