简体   繁体   English

viewmodel Android 中的动态参数

[英]Dynamic parameters in viewmodel Android

How can I reuse the parameter of a ViewModel in Android?如何在 Android 中重用 ViewModel 的参数? I have a recycle viewer filled with data from a database based on a parameter: selectedDate .我有一个循环查看器,其中填充了基于参数的数据库中的数据: selectedDate How can I reuse it in a fragment, in this way to refresh the recycle viewer?如何在片段中重用它,以这种方式刷新回收查看器? So far I'm using a ViewModelFactory :到目前为止,我正在使用ViewModelFactory

public class MyViewModelFactory implements ViewModelProvider.Factory {

    private Application mApplication;
    private String mParam;


    public ShiftViewModelFactory(Application mApplication, String param) {
        mApplication=mApplication;
        mParam = param;
    }


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

And I'm loading it in an onCreateView :我将它加载到onCreateView中:

myViewModel = ViewModelProviders.of(this, new myViewModelFactory(selectedDate)).get(MyViewModel.class);

How can I change the parameter selectedDate and then refresh the data?如何更改参数selectedDate然后刷新数据?

Here is my ViewModel这是我的视图模型

public class ShiftsViewModel extends ViewModel implements IShiftMapCallbackListener {

private MutableLiveData<List<ShiftModel>> coworkerList;
private MutableLiveData<String> messageError;
private IShiftMapCallbackListener coworkerInfoCallbackListener;


public ShiftsViewModel() {

    coworkerInfoCallbackListener = this;
}

private void loadCoworkerList() {
    final List<ShiftModel> tempList = new ArrayList<>();
    DatabaseReference coworkerRef = FirebaseDatabase.getInstance()
            .getReference(Common.MAP)
            .child(Common.DATA)
            .child(selectedDate);

    coworkerRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for (DataSnapshot itemSnapshot : dataSnapshot.getChildren())
                if (!itemSnapshot.child("Operator").getValue().equals("")) {
                    ShiftModel model = itemSnapshot.getValue(ShiftModel.class);
                    tempList.add(model);
                }
            coworkerInfoCallbackListener.onCoworkerInfoLoadSuccess(tempList);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            coworkerInfoCallbackListener.onCoworkerInfoLoadFailed(databaseError.getMessage());
        }
    });
}

public MutableLiveData<List<ShiftModel>> getCoworkerList() {
    if (coworkerList == null){
        coworkerList = new MutableLiveData<>();
        messageError = new MutableLiveData<>();

        loadCoworkerList();
    }
    return coworkerList;
}

public MutableLiveData<String> getMessageError() {
    return messageError;
}

@Override
public void onCoworkerInfoLoadSuccess(List<ShiftModel> shiftModels) {
    coworkerList.setValue(shiftModels);
}

@Override
public void onCoworkerInfoLoadFailed(String message) {
    messageError.setValue(message);
}
}

The parameter I want to change is selectedDate :我要更改的参数是selectedDate

DatabaseReference coworkerRef = FirebaseDatabase.getInstance()
            .getReference(Common.MAP)
            .child(Common.DATA)
            .child(selectedDate);

Then in the fragment I call it like this:然后在片段中我这样称呼它:

shiftsViewModel.getCoworkerList().observe(this, shiftModel -> {

        shiftMapAdapter = new ShiftMapAdapter(ShiftsFragment.this.getContext(), shiftModel, operatorShow);

        coworker_recycler.setAdapter(shiftMapAdapter);
        coworker_recycler.setLayoutAnimation(layoutAnimationController);
    });

So how can I change the date let say from "2019-11-14" to "2019-11-15"那么如何将日期从“2019-11-14”更改为“2019-11-15”

You may want to shift from using factory parameter to using what essentially is view model data filter.您可能希望从使用工厂参数转变为使用本质上是视图 model 数据过滤器。 You'll have to:你必须:

  1. Define your "filter": private final MutableLiveData<String> filter = new MutableLiveData<>();定义你的“过滤器”: private final MutableLiveData<String> filter = new MutableLiveData<>();
  2. Init your "filter" with some value once model is created (probably with value you are already currently passing into factory: filterText.setValue(...)创建 model 后,使用某个值初始化您的“过滤器”(可能使用您当前已经传递给工厂的值: filterText.setValue(...)
  3. Define your view model's live data via transformation (input is what holds your filter):通过转换定义视图模型的实时数据(输入是过滤器的内容):
Transformations.switchMap(
    filter, (Function<String, LiveData<...>) input -> {
...
}
  1. Define some way of changing your filter - every such change will get you fresh data observation:定义某种更改过滤器的方法 - 每一次这样的更改都会让您获得新的数据观察:
void setFilter(String filter) {
    this.filter.setValue(filter);
}

You can do this without the ViewModelFactory.. just create function to set & update selectedDate inside your ViewModel, and call that function in your view您可以在没有 ViewModelFactory 的情况下执行此操作。只需创建 function 以在您的 ViewModel 中设置和更新 selectedDate,然后在您的视图中调用 function

class FooViewModel: ViewModel() {

    var selectedDate: String = ""

    fun setDate(date: String) {
        selectedDate = date
    }
}

Any value passed to variabel inside your ViewModel is shared to any view that apply the same ViewModel, yo sour activity & fragment can get the same value传递给 ViewModel 中 variabel 的任何值都将共享给应用相同 ViewModel 的任何视图,你的酸活动和片段可以获得相同的值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android kotlin 使用 ViewModelFactory 将动态参数/参数传递给 ViewModel - Android kotlin passing dynamic arguments/parameters to ViewModel with ViewModelFactory 如何在使用viewmodel时将动态参数传递给android中的api - How to pass dynamic parameters to rest api in android when using viewmodel 将查询参数传递给 Android 应用程序中的 LiveData/Viewmodel - Passing query parameters to LiveData/Viewmodel in Android app 了解Android架构组件示例GithubBrowserSample:ViewModelModule,ViewModel参数 - Understanding Android Architecture Components example GithubBrowserSample: ViewModelModule, ViewModel parameters Android Kotlin 从带参数的视图中调用 ViewModel function - Android Kotlin Calling ViewModel function from View with Parameters Android Retrofit-发送动态数量的POST参数 - Android Retrofit - send dynamic number of POST parameters 在MvvmCross中将参数从ViewModel传递到ViewModel的替代方法 - Alternatives on passing parameters from ViewModel to ViewModel in MvvmCross 使用 Dagger 2 将 ViewModel 注入 Fragment,带参数 - Injecting ViewModel into the Fragment with Dagger 2, with parameters 在Android中使用Dagger2时如何使用AssistedInject将动态值作为参数传递给ViewModel - How to use AssistedInject to pass dynamic value as a parameter to ViewModel when using Dagger2 in Android Android ViewModel 到 Model 事件 - Android ViewModel to Model events
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM