码迷,mamicode.com
首页 > 其他好文 > 详细

RecyclerView基本用法

时间:2016-07-11 00:47:01      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

1. 在gradle.build的dependencies中添加RecyclerView需要的包

compile ‘com.android.support:cardview-v7:23.4.0‘
compile ‘com.android.support:recyclerview-v7:23.4.0‘

添加完后记得要Sync Gradle

 

2. 在布局文件中添加控件RecyclerView. 

<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content">

</android.support.v7.widget.RecyclerView>

3.在Activity中找到RecyclerView并设置LayoutManager和Adapter

RecyclerView rv;
NewsAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rv = (RecyclerView) findViewById(R.id.rv);
rv.setLayoutManager(new LinearLayoutManager(this));
rv.setAdapter(adapter);

}

4. 写Adapter

class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.VH> {
String[] data = {"a","b","c","d","e"};

  //创建ViewHoler
@Override
public VH onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_item,parent,false);
VH vh = new VH(view);
return vh;
}

  //数据绑定
@Override
public void onBindViewHolder(VH holder, int position) {
holder.title.setText(data[position]);

}

@Override
public int getItemCount() {
return data.length;
}

  //内部类VH 保存所有view
class VH extends RecyclerView.ViewHolder {
public TextView title;
public VH(View itemView) {
super(itemView);
title = (TextView)itemView.findViewById(R.id.title);
}
}


}






 

RecyclerView基本用法

标签:

原文地址:http://www.cnblogs.com/yidan621/p/5658938.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!