我在我的应用程序中使用LiveData,我有一个Model和一个ViewModel。这是我的Model和ViewModel类。
public class HomeMenuModel {
String id;
String title;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
public class DashboardViewModel {
public MutableLiveData < HomeMenuModel > menuList = new MutableLiveData < > ();
private List<String> idList = new ArrayList<>();
private List<String> idLists = new ArrayList<>();
private List<String> titleList = new ArrayList<>();
public MutableLiveData < HomeMenuModel > setupMenu(Context mCtx) {
idList.add("homeData");
idList.add("homeVoiceAndSMS");
idList.add("homeRoaming");
idList.add("homeDigital");
titleList.add(mCtx.getString(R.string.homeData));
titleList.add(mCtx.getString(R.string.homeVoiceAndSMS));
titleList.add(mCtx.getString(R.string.homeRoaming));
titleList.add(mCtx.getString(R.string.homeDigital));
HomeMenuModel homeMenuModel = new HomeMenuModel();
for (int i = 0; i < idList.size(); i++) {
homeMenuModel.setId(idList.get(i));
homeMenuModel.setTitle(titleList.get(i));
}
menuList.setValue(homeMenuModel);
return menuList;
}
}
我试着在setupMenu中添加idList和titleList,并从函数中返回menuList。我在我的Fragment中调用了setupMenu函数,代码如下。
public class HomeFragment extends BaseFragment {
static final String TAG = "FragmentHome";
private FragmentHomeBinding mBinding;
@Inject
DashboardViewModel dashboardViewModel;
private Context mCtx;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
AndroidSupportInjection.inject(this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_home, container, false);
View v = mBinding.getRoot();
mCtx = mBinding.getRoot().getContext();
initEvent();
return v;
}
private void initEvent() {
mBinding.setDashboardView(dashboardViewModel);
dashboardViewModel.setupMenu(mCtx).observe(this, data - > {
Log.e("menuList", data.getTitle());
});
}
@Override
public String getTagFragment() {
return TAG;
}
}
我在一个HomeFragment中记录了menuList,但不幸的是,我只得到了观察到的id或title的最后一项。
我错过了什么?
为什么我只得到最后一项结果,而不是在setupMenu函数中创建的4个结果?我怎样才能得到所有4个结果?
任何帮助都将是非常感激的。
谢谢你的帮助。
你只更新最后的信息 homeMenuModel
.要获得所有的项目,你应该创建 MutableLiveData<ArrayList<HomeMenuModel>>
. 试试这个
private MutableLiveData<ArrayList<HomeMenuModel>> menuList = new MutableLiveData<ArrayList<HomeMenuModel>>()
ArrayList<HomeMenuModel> list = new ArrayList<HomeMenuModel>()
for (int i = 0; i < idList.size(); i++) {
HomeMenuModel homeMenuModel = new HomeMenuModel();
homeMenuModel.setId(idList.get(i));
homeMenuModel.setTitle(titleList.get(i));
list.add(homeMenuModel)
}
menuList.setValue(list);