主要参照一下两篇文章
http://blog.csdn.net/a10615/article/details/51268022
http://blog.csdn.net/loveyaozu/article/details/53035587
1、在AndroidStudio的build.gradle中添加下面的一句话
注意 com.android.support:appcompat和RecyclerView的版本号保持一致!
2、重新编译一下AndroidStudio。如果写代码时,与RecyvlerView相关的都显示红色,而且Alt+enter无法导入正确的包,退出AndroidStudio再重新进入工程即可!
参考文档
http://www.android100.org/html/201602/12/214931.html
在Activity的主布局文件中添加
<android.support.v7.widget.RecyclerView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/my_recyclerview" />然后添加RecyclerView中的item布局 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <ImageView android:layout_width="match_parent" android:layout_height="wrap_content" android:src="@mipmap/ic_action_gplus" android:id="@+id/simple_image" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" android:id="@+id/simple_text"/> </LinearLayout>很简单,一个线性布局,一个图片,一个文字,而且图片是定义死的。public class MySimpleRecyclerViewAdapter extends RecyclerView.Adapter<MySimpleRecyclerViewAdapter.MySimpleViewHolder> { private Context mContext; private ArrayList<String> mData; public MySimpleRecyclerViewAdapter(Context context,ArrayList<String> data) { mContext = context; mData = data; } @Override public MySimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { //创建布局,并保存在ViewHolder中 return new MySimpleViewHolder(LayoutInflater.from(mContext).inflate(R.layout.simple_item, parent, false)); } @Override public void onBindViewHolder(MySimpleViewHolder holder, int position) { //设置具体的数据 if (mData!= null) { holder.mTextView.setText(mData.get(position)); } } @Override public int getItemCount() { return mData == null ? 0: mData.size(); } public static class MySimpleViewHolder extends RecyclerView.ViewHolder{ TextView mTextView; ImageView mImageView; public MySimpleViewHolder(View view){ super(view); mTextView = (TextView)view.findViewById(R.id.simple_text); mImageView = (ImageView)view.findViewById(R.id.simple_image); } } } 在Adapter内部定义自己的ViewHolder,这个主要保存相关的控件对象,方便后面更新控件相关的信息,比如文字或者图片等。
定义Adapter,只要是继承自RecyclerView的Adapter,AndroidStudio就会提示实现onCreateViewHolder onBindViewHolder getItemCount三个接口,每个的作用看代码就会立即明白。