当我在微调器中选择一些项目时,我想在RecyclerView中刷新我的数据。 RecyclerView被放置在标签式活动中的片段中,My RecyclerView从带有livingata的房间填充。我为RecyclerView创建观察者,但我不明白如何改变观察者或做其他事情。 可能我需要重新创建此标签... 请告诉我我能做些什么。
当我创建新的观察者时,我在RecyclerView中获取新数据,但是当我与这些数据进行交互时,我看到所有旧的观察者都是现场的,并对我的活动作出反应。
如何从数据库中查询其他数据并将其传递给观察者或创建新观察者并删除旧观察者?
我的片段
public class AllSitesFragment extends Fragment implements AdapterView.OnItemSelectedListener {
@BindView(R.id.recycler_view)
RecyclerView recyclerView;
@BindView(R.id.tvEmptyMessage)
TextView tvEmptyMessage;
@BindView(R.id.spinner)
Spinner spinner;
private WebSitesViewModel mWebSitesViewModel;
private MyRecViewAdapter adapter;
public AllSitesFragment() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_all_sites, container, false);
ButterKnife.bind(this, v);
setHasOptionsMenu(true);
mWebSitesViewModel = ViewModelProviders.of(this).get(WebSitesViewModel.class);
adapter = new MyRecViewAdapter(getContext(), mWebSitesViewModel, AllSitesFragment.this );
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(adapter);
//Observer
mWebSitesViewModel.getAllWebSites().observe(this, new Observer<List<WebSites>>() {
@Override
public void onChanged(@Nullable final List<WebSites> webSites) {
adapter.setWebSites(webSites);
if (adapter.getmWebSites().size() == 0) {
tvEmptyMessage.setText(R.string.not_saved_sites);
tvEmptyMessage.setVisibility(View.VISIBLE);
} else {
tvEmptyMessage.setVisibility(View.INVISIBLE);
}
}
});
spinner.setOnItemSelectedListener(this);
mWebSitesViewModel.getAllWebSites().removeObservers(getActivity());
return v;
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
// Refresh
break;
case 1:
//Refresh
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
答案 0 :(得分:0)
您需要在viewModel中过滤getAllWebSites()
函数的结果,因此您需要在该viewModel中设置一个setter来设置/更新过滤器。
您可以在viewModel中使用MutableLiveData
变量,该变量将用作过滤网站集的参数。
这可以通过switchMap转换完成。
这将是这样的(非功能性,适应您的需求):
<强>视图模型强>
public class SitesViewModel extends AndroidViewModel {
private final YourManager yourManager;
private final LiveData<WebSites> webSites;
private final MutableLiveData<YourItem> yourItemFilter;
public SitesViewModel(Application application) {
super(application);
yourManager = new YourManager();
yourItemFilter = new MutableLiveData<>();
webSites = Transformations.switchMap(yourItemFilter, input -> yourManager.getAllWebSites(input));
}
public void setYourItemFilter(YourItem filter) {
yourItemFilter.setValue(filter);
}
public LiveData<WebSites> getAllWebSites() {
return webSites;
}
}
然后在您的活动中,只需在所选项目上设置过滤器值:
<强>活动强>
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
YourItem item = (YourItem) parent.getItemAtPosition(position);
mWebSitesViewModel.setYourItemFilter(item);
break;
case 1:
...
}
}