Write a whole two days of RecyclerView, ListView, divide type RecyclerView, divide type ListView, really write bored, so simply to relax, write a blog to do a tidy up.
Everything should be learned step by step, don’t try to eat a big fat, so let’s start with the simplest.
Start with the simplest RecyclerView:
Step 1: Write a RecyclerView in the layout
Step 2: Instantiate
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
Step 3: Get the data you need
getData(); Private void getData() {beanList = new ArrayList<>(); for (int i = 0; i < 100; I ++) {String bean = new String(" I "+ I + "); beanList.add(bean); }}Copy the code
Step 4: Create and set up the adapter and pass the data
MyRvAdapter adapter = new MyRvAdapter(mContext, beanList);
recyclerView.setAdapter(adapter);Copy the code
The corresponding adapter classes are as follows:
public class MyRvAdapter extends RecyclerView.Adapter { private final Context mContext; private final List beanList; public MyRvAdapter(Context mContext, List beanList) { this.mContext=mContext; this.beanList=beanList; } @override public recyclerView. ViewHolder onCreateViewHolder(ViewGroup parent); int viewType) { return new MyViewHolder(View.inflate(mContext,R.layout.item_layout,null)); } /** * bind ViewHolder * @param holder * @param position */ @override public void onBindViewHolder(recyclerViewholder holder, int position) { //1. MyViewHolder MyViewHolder = (MyViewHolder) holder; MyViewHolder MyViewHolder = (MyViewHolder) holder; //2. Assemble data myviewholder. setData(position); } @override public int getItemCount() {return beanlist.size (); } class MyViewHolder extends RecyclerView.ViewHolder{ TextView name; public MyViewHolder(View itemView) { super(itemView); name= (TextView) itemView.findViewById(R.id.name); } public void setData(int position) { name.setText(beanList.get(position)); // Make sure you don't get confused. // for (int i=0; iCopy the code
Finally!!!!! Must not forget!!
RecycleView not only needs to set up the adapter but also set up the layout manager, otherwise the image will not display
GridLayoutManager manager = new GridLayoutManager(this, 1);
recyclerView.setLayoutManager(manager);Copy the code
Complete the ~