RecyclerView 介紹 01

HalZhang發表於2015-02-27

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.  
    3.     private List<String> mDatas = new ArrayList<>(0);
    4.  
    5.     public MyRecyclerAdapter(List<String> datas) {
    6.         if (datas != null) {
    7.             mDatas.addAll(datas);
    8.         }
    9.     }
    10.  
    11.     public static final class ViewHolder extends RecyclerView.ViewHolder {
    12.  
    13.         private final TextView textView;
    14.         private final Button button;
    15.  
    16.  
    17.         public ViewHolder(View itemView) {
    18.             super(itemView);
    19.             textView = (TextView) itemView.findViewById(R.id.item_text);
    20.             button = (Button) itemView.findViewById(R.id.item_button);
    21.             button.setOnClickListener(new View.OnClickListener() {
    22.  
    23.                 @Override
    24.                 public void onClick(View v) {
    25.                     Toast.makeText(v.getContext(), String.valueOf(getPosition()), Toast.LENGTH_SHORT).show();
    26.                 }
    27.             });
    28.         }
    29.  
    30.         public TextView getTextView() {
    31.             return textView;
    32.         }
    33.  
    34.         public Button getButton() {
    35.             return button;
    36.         }
    37.     }
    38.  
    39.     @Override
    40.     public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    41.         View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, null);
    42.         return new ViewHolder(view);
    43.     }
    44.  
    45.     @Override
    46.     public void onBindViewHolder(ViewHolder holder, int position) {
    47.         holder.getButton().setText(String.valueOf(position));
    48.         holder.getTextView().setText(mDatas.get(position));
    49.     }
    50.  
    51.     @Override
    52.     public int getItemCount() {
    53.         return mDatas.size();
    54.     }
    55.  
    56. }

     

  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

 

相關文章