RecyclerView是Android support v7裡面是一個自定義控制元件。用來顯示大量資料集合。類似ListView和GridView這兩個控制元件,RecyclerView同樣可以實現,甚至更好。
以前我們在實現ListView和GridView的時候,都會定義一個ViewHolder用於優化UI效能【詳見】,RecycleView的實現,已經是自帶ViewHolder的實現。請看示例。
-
實現Adapter,定義每個Item的佈局UI和資料。
-
public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.ViewHolder> {
-
-
private List<String> mDatas = new ArrayList<>(0);
-
-
public MyRecyclerAdapter(List<String> datas) {
-
if (datas != null) {
-
mDatas.addAll(datas);
-
}
-
}
-
-
public static final class ViewHolder extends RecyclerView.ViewHolder {
-
-
private final TextView textView;
-
private final Button button;
-
-
-
public ViewHolder(View itemView) {
-
super(itemView);
-
textView = (TextView) itemView.findViewById(R.id.item_text);
-
button = (Button) itemView.findViewById(R.id.item_button);
-
button.setOnClickListener(new View.OnClickListener() {
-
-
@Override
-
public void onClick(View v) {
-
Toast.makeText(v.getContext(), String.valueOf(getPosition()), Toast.LENGTH_SHORT).show();
-
}
-
});
-
}
-
-
public TextView getTextView() {
-
return textView;
-
}
-
-
public Button getButton() {
-
return button;
-
}
-
}
-
-
@Override
-
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
-
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, null);
-
return new ViewHolder(view);
-
}
-
-
@Override
-
public void onBindViewHolder(ViewHolder holder, int position) {
-
holder.getButton().setText(String.valueOf(position));
-
holder.getTextView().setText(mDatas.get(position));
-
}
-
-
@Override
-
public int getItemCount() {
-
return mDatas.size();
-
}
-
-
}
-
-
初始化RecyclerView
設定Adapter和LayoutManager。LayoutManager定義了每個Item的排列形式。官方提供兩種實現,LinearLayoutManager和GridLayoutManager,當然我們也可以根據需求,自己實現LayoutManager。
-
recyclerView = (RecyclerView) findViewById(R.id.recycler);
-
MyRecyclerAdapter adapter = new MyRecyclerAdapter(Datas.getDatas(1000));
-
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
-
recyclerView.setLayoutManager(layoutManager);
-
recyclerView.setAdapter(adapter);
-
RecyclerView就是這麼簡單。
原始碼:GitHub