如何更新房间返回的列表

时间:2019-08-15 04:47:11

标签: android android-room android-viewmodel

我想在Recyclerview中显示动物列表,该列表中有10只动物要启动,我只想从Room数据库中返回3只动物来启动,并在菜单中为用户提供选项,以返回列表大小为3、5或7只动物。

我尝试了以下     -在ViewModel中更新listSize。     -再次调用ViewModel。     -在ViewModel中调用getAnimals方法

MainActivity onCreate()

int listSize = 3;


ViewModelFactory factory = new ViewModelFactory(getApplication, listSize);
ViewModel viewmodel = ViewModelProviders.of(this, factory).get ViewModel.class);

viewModel.getAnimals().observe(this, new Observer<List<Animal>>() {
    @Override
    public void onChanged(@Nullable List<Animal> animal) {               
        adapter.setAnimal(animal);
            }
        });

ViewModelFactory

public class ViewModelFactory implements ViewModelProvider.Factory {
    private int listSize;
    private Application application;

    public ViewModelFactory(Application application, int size) {
        this.listSize = size;
        this.application = application;
    }

    public <T extends ViewModel> T create(Class<T> modelClass) {
        if(modelClass.isAssignableFrom(ViewModel.class)){
            return (T) new ViewModel(application, listSize);
        }
        throw new IllegalArgumentException("Unknown view model class");
    }
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch(item.getItemId()) {
        case (R.id.delete_all):
            viewModel.deleteAll();
            return true;
        case (R.id.menu_display_3):
            viewModel.setListSize(3);
            return true;
        case(R.id.menu_display_5):
            setListSize(5);
            return true;
        case(R.id.menu_display_7):
            setListSize(7);
            return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}


ViewModel


public class AnimalViewModel extends AndroidViewModel {

    private int listSize;
    private AnimalRepository repository;
    private LiveData<List<Animal>> mAllAnimals;

    public AnimalViewModel(Application application, int size) { 
        super(application); 
        this.listSize = size;
        repository = new AnimalRepository(application, listSize); 
        mAllAnimals = repository.getAllAnimals(); 
    }

    LiveData<List<Animal>> getAnimals() {
        return mAllAnimals;
    }

    public void setListSize(int listSize) {
        this.listSize = listSize;
    }
}

当用户选择尺寸时,我希望看到RecyclerView中显示许多动物。

0 个答案:

没有答案