RecyclerView使用

導入recyclerviewv7包android

在layout中添加recyclerViewide

1 <android.support.v7.widget.RecyclerView
2         android:id="@+id/recyclerView"
3         android:layout_gravity="center"
4         android:background="@android:color/holo_blue_bright"
5         android:layout_width="match_parent"
6         android:layout_height="match_parent"/>

寫item的layout,這裏是recycler_view_item.xmlthis

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:orientation="vertical" android:layout_width="match_parent"
 4     android:background="@android:color/white"
 5     android:layout_marginTop="20dp"
 6     android:layout_height="match_parent">
 7     <TextView
 8         android:layout_width="match_parent"
 9         android:layout_height="wrap_content"
10         android:layout_marginLeft="10dp"
11         android:id="@+id/recyclerViewText"
12         android:textColor="@android:color/black"
13         android:textSize="18sp"/>
14 </LinearLayout>

和listView同樣,須要適配器spa

 1 public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.TextViewHolder>{
 2 
 3     private Context context;
 4     private List<TextModel> data = new ArrayList<TextModel>();
 5 
 6     public RecyclerViewAdapter(Context context, List<TextModel> data){
 7         this.context = context;
 8         this.data = data;
 9     }
10 
11     @Override
12     public TextViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
13         TextViewHolder holder = new TextViewHolder(LayoutInflater.from(context).inflate(R.layout.recycler_view_item, parent, false));
14         return holder;
15     }
16 
17     @Override
18     public void onBindViewHolder(TextViewHolder holder, int position) {
19         holder.text.setText("" + data.get(position).getText());
20     }
21 
22     @Override
23     public int getItemCount() {
24         return data.size();
25     }
26 
27     class TextViewHolder extends RecyclerView.ViewHolder{
28 
29         TextView text;
30         public TextViewHolder(View itemView) {
31             super(itemView);
32             text = (TextView) itemView.findViewById(R.id.recyclerViewText);
33             
34         }
35     }
36 }

這裏TextModel只有一個屬性,textcode

在activity中使用xml

1 List<TextModel> data = new ArrayList<TextModel>();
2 TextModel text = new TextModel();
3 text.setText("xxx");    
4 data.add(text);        //傳的值是個list
5 recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
6 recyclerView.setLayoutManager(new LinearLayoutManager(this));
7 recyclerView.setAdapter(new RecyclerViewAdapter(MainActivity.this, data));
相關文章
相關標籤/搜索