我在fragmentRecycler中遇到显示数据的问题我正在使用改装来获得json使用viewModel和liveData观察活动配置并从中生存但我不知道如何将这些响应显示为项目的在我的碎片回收器视图中这是我在创建方法代码上的片段:-
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
voucherViewModel model = ViewModelProviders.of(getActivity()).get(voucherViewModel.class);
model.getVoucher().observe(getActivity(), new Observer<List<Voucher>>() {
@Override
public void onChanged(@Nullable List<Voucher> vouchers) {
Log.e("on change", "onChanged: " );
adapter = new homeRecycleViewAdapter(getContext(),vouchers );
recyclerView.setLayoutManager(new LinearLayoutManager(context));
recyclerView.setAdapter(adapter);
}
});
}//end onCreate
我的OnCreateView方法代码:-
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.home_fragment_layout, container, false);
adapter = new homeRecycleViewAdapter(context);
recyclerView = view.findViewById(R.id.homeRecyclerViewID);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(adapter);
//return inflated view
return view;
}
所以我希望得到帮助:(
首先不要在片段的onCreate((中使用任何视图。这里没有创建视图,因此可能会出现错误。
其次,让onCreteView只返回正在膨胀的视图。
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.home_fragment_layout, container, false)
return view;
}
充气完成后,您将在onViewCreated上获得回调。在这里,你可以访问所有的视图,比如你的回收视图。在这里,它们将被充气。
@Override
void onViewCreated(View view, Bundle savedInstanceState) {
homeRecycleViewAdapter adapter = new homeRecycleViewAdapter(context, vouchers);
recyclerView = view.findViewById(R.id.homeRecyclerViewID);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(adapter);
super.onViewCreated(view, savedInstanceState)
}