添加依赖
compile 'com.android.support:appcompat-v7:24.2.0'
compile 'com.android.support:recyclerview-v7:24.2.0'
compile 'com.android.support:cardview-v7:24.2.0'
<strong>注意:</strong>support包的版本要一致,即-v
后面的参数要相同。
列表项布局
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp"
card_view:cardCornerRadius="2dp">
<TextView
android:id="@+id/tv_text"
android:padding="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"/>
</android.support.v7.widget.CardView>
<strong>注意:</strong>命名空间。
Adapter写法
public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.HomeViewHolder> {
private Context context;
private List<String> list;
public HomeAdapter(Context context,List<String> list){
this.context = context;
this.list = list;
}
@Override
public HomeAdapter.HomeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new HomeViewHolder(LayoutInflater.from(context).inflate(R.layout.item,parent,false));
}
@Override
public void onBindViewHolder(HomeViewHolder holder, int position) {
holder.textView.setText(list.get(position));
}
@Override
public int getItemCount() {
return list.size();
}
// 创建Holder类
public static class HomeViewHolder extends RecyclerView.ViewHolder{
TextView textView;
public HomeViewHolder(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.tv_text);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(""ItemOnClick"","item"+getAdapterPosition());
}
});
}
}
}
使用RecyclerView
// 必须有设置布局
// 线性显示 类似于listview
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
// 线性宫格显示 类似于grid view
// mRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));
// 线性宫格显示 类似于瀑布流
// mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, OrientationHelper.VERTICAL));
mRecyclerView.setAdapter(new NormalRecyclerViewAdapter(this));