fragment 中 mRecyclerView.setLayoutManager()报错
代码是按照老师视频来的,稍有改动
只是从MainActivity 变为Fragment
Fragment中 onCreateView代码:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_fragment2, container, false); initDatas(); mRecyclerView = view.findViewById(R.id.item2); mRVAdapter = new RVAdapter(getActivity(),mData); mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false)); mRecyclerView.setItemAnimator(new DefaultItemAnimator()); mRecyclerView.setAdapter(mRVAdapter); mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(),DividerItemDecoration.VERTICAL)); return view; }
adapter代码:
public class RVAdapter extends RecyclerView.Adapter<MyViewHolder> { private Context context; private List<String> data; public RVAdapter(Context context , List<String> data){ this.context = context; this.data = data; } @NonNull @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { //创建ViewHolder View view = LayoutInflater.from (viewGroup.getContext ()).inflate (R.layout.item2,viewGroup,false); MyViewHolder viewHolder = new MyViewHolder(view); return viewHolder; } @Override public void onBindViewHolder(@NonNull MyViewHolder holder, int pos) { // 绑定viewholder holder.tv.setText(data.get(pos)); } @Override public int getItemCount() { return data.size(); } } class MyViewHolder extends RecyclerView.ViewHolder{ TextView tv; public MyViewHolder(@NonNull View arg0) { super(arg0); tv = arg0.findViewById(R.id.item2); } }