我有一个垂直滚动的recyclerview(verticalRV)。此recyclerview(horizontalRV)中的每个项目都是Horizontal recyclerview。
在verticalRV itemViewHodler中尝试从viewmodel获取数据并观察任何chages并相应地更新horizontalRV适配器。
但是观察者是onChanged
方法没有得到调用。
我已经实现了LifecycleOwner接口来管理视图持有者的生命周期with livedata并相应地从垂直RV的适配器设置状态
public class VeritcalRVHolderItem implements LifecycleOwner {
private static final String TAG = LDFeedListAdapterHolder.class.getSimpleName();
private final FragmentActivity activity;
private final RvHorizontalListAdapter adapter;
private RecyclerView rvHorizontalList;
public VeritcalRVHolderItem(Context context, View itemView, FragmentActivity activity) {
super(context, itemView);
this.activity = activity;
rvHorizontalList = itemView.findViewById(R.id.rvHorizontalList);
LinearLayoutManager layout = new LinearLayoutManager(getContext(), LinearLayout.HORIZONTAL, false);
rvHorizontalList.setLayoutManager(layout);
adapter = new RvHorizontalListAdapter(this.activity);
rvHorizontalList.setAdapter(adapter);
LDViewModel LDViewModel = ViewModelProviders.of(activity).get(LDViewModel.class);
LDViewModel.getTopicsForFeed().observe(this, new Observer<List<Topic>>() {
@Override
public void onChanged(List<Topic> topics) {
//adding live discussion model at first position
adapter.updateLiveList(topics);
adapter.notifyItemChanged(0);
Log.d(TAG, "discussion model calls");
}
});
}
private LifecycleRegistry lifecycleRegistry;
public void onAppear() {
lifecycleRegistry.markState(Lifecycle.State.CREATED);
}
public void onDisappear() {
lifecycleRegistry.markState(Lifecycle.State.DESTROYED);
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return lifecycleRegistry;
}
}
请让我知道我在这里失踪了什么。
从我的角度来看,最好将数据观察到你的fragment
或activity
并将数据传递给recyclerview
,在Recyclerview
中覆盖方法getItemViewType
,从getItemViewType
你可以处理vertical
项目和horizontal
项目。
例:-
public class ViewModel extends AndroidViewModel {
private MutableLiveData<Model> modelMutableLiveData;
public ViewModel(@NonNull Application application) {
super(application);
modelMutableLiveData = new MutableLiveData<>();
}
public MutableLiveData<Model> getModelMutableLiveData() {
return modelMutableLiveData;
}
public final void yourMethod(Model model) {
// Do something
}
}
片段类
public class Fragment extend BaseFragment {
private void initViewModelData() {
viewModel.getModelMutableLiveData().observe(this, new Observer<Model>() {
@Override
public void onChanged(@Nullable Model model) {
if (model != null) {
modelList.add(model);
adapter.notifyItemInserted(modelList.size()- 1);
}
}
});
}
}
RecyclerViewAdapter
class RecyclerViewAdater extend Adapter<ViewHolder>{
@Override
public int getItemViewType(int position) {
return mDataList.get(position).getContainerType();
}
}
基于此,您可以编写您的recyclerView
代码