RecyclerView 介绍 01

时间:2021-12-05 16:34:21

RecyclerView是Android support v7里面是一个自定义控件。用来显示大量数据集合。类似ListView和GridView这两个控件,RecyclerView同样可以实现,甚至更好。

以前我们在实现ListView和GridView的时候,都会定义一个ViewHolder用于优化UI性能【详见】,RecycleView的实现,已经是自带ViewHolder的实现。请看示例。

  1. 实现Adapter,定义每个Item的布局UI和数据。
    1. public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.ViewHolder> {
    2.     private List<String> mDatas = new ArrayList<>(0);
    3.     public MyRecyclerAdapter(List<String> datas) {
    4.         if (datas != null) {
    5.             mDatas.addAll(datas);
    6.         }
    7.     }
    8.     public static final class ViewHolder extends RecyclerView.ViewHolder {
    9.         private final TextView textView;
    10.         private final Button button;
    11.         public ViewHolder(View itemView) {
    12.             super(itemView);
    13.             textView = (TextView) itemView.findViewById(R.id.item_text);
    14.             button = (Button) itemView.findViewById(R.id.item_button);
    15.             button.setOnClickListener(new View.OnClickListener() {
    16.                 @Override
    17.                 public void onClick(View v) {
    18.                     Toast.makeText(v.getContext(), String.valueOf(getPosition()), Toast.LENGTH_SHORT).show();
    19.                 }
    20.             });
    21.         }
    22.         public TextView getTextView() {
    23.             return textView;
    24.         }
    25.         public Button getButton() {
    26.             return button;
    27.         }
    28.     }
    29.     @Override
    30.     public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    31.         View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, null);
    32.         return new ViewHolder(view);
    33.     }
    34.     @Override
    35.     public void onBindViewHolder(ViewHolder holder, int position) {
    36.         holder.getButton().setText(String.valueOf(position));
    37.         holder.getTextView().setText(mDatas.get(position));
    38.     }
    39.     @Override
    40.     public int getItemCount() {
    41.         return mDatas.size();
    42.     }
    43. }
  2. 初始化RecyclerView

    设置Adapter和LayoutManager。LayoutManager定义了每个Item的排列形式。官方提供两种实现,LinearLayoutManager和GridLayoutManager,当然我们也可以根据需求,自己实现LayoutManager。

    1. recyclerView = (RecyclerView) findViewById(R.id.recycler);
    2. MyRecyclerAdapter adapter = new MyRecyclerAdapter(Datas.getDatas(1000));
    3. RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
    4. recyclerView.setLayoutManager(layoutManager);
    5. recyclerView.setAdapter(adapter);

RecyclerView就是这么简单。

源码:GitHub