设置依赖
在module的build.gradle里添加如下代码
dependencies {
...
compile 'com.android.support:appcompat-v7:26.0.2'
compile 'com.android.support:design:26.0.2'
...
}
在布局文件中定义
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
建立Item的布局
我们还需要建立一个布局文件用于自定义RecyclerView中每个条目的布局,在这里我将这个布局命名为item_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tv_text"
android:layout_width="match_parent"
android:gravity="center"
android:layout_height="40dp"
android:layout_weight="1"/>
</LinearLayout>
建立一个Bean类
这个类主要用于对数据进行包装(一般会在Bean类里放多个数据,这里只是为了简便只放一种数据)
public class ItemBean {
private String text;
public void setText(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
自定义Adapter和ViewHolder
adapter 用于将数据绑定到每个Item的View上,而ViewHolder相当于item_layout的Activity类,用于获取item_layout.xml里的控件。
public class MyAdapter extends RecyclerView.Adapter {
// 要在Item上显示的数据
List<ItemBean> mDataSet = new ArrayList<>();
Context mContext;
public MyAdapter(Context context){
mContext=context;
}
// 用于获取ViewHolder
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView=LayoutInflater.from(mContext).inflate(R.layout.item_layout, parent, false);
return new MyViewHolder(itemView);
}
// 将数据与ViewHolder绑定
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
MyViewHolder mHolder= (MyViewHolder) holder;
ItemBean itemBean=mDataSet.get(position);
mHolder.textView.setText(itemBean.getText());
}
// 获取Item的数量
@Override
public int getItemCount() {
return mDataSet.size();
}
// 以下五个方法是我自定义的,用来对数据进行一系列操作
public void refreshItems(List<ItemBean> items) {
mDataSet.clear();
mDataSet.addAll(items);
notifyDataSetChanged();
}
public void addItems(List<ItemBean> items) {
mDataSet.addAll(items);
}
public void addItem(ItemBean item){
mDataSet.add(item);
}
public void deleteItem(int position) {
mDataSet.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(0, mDataSet.size() - 1);
}
// ViewHolder用于获取Item上的控件
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView textView;
public MyViewHolder(View itemView) {
super(itemView);
textView=(TextView) itemView.findViewById(R.id.tv_text);
//添加点击事件
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(mContext,"第"+getLayoutPosition()+"项被选中",Toast.LENGTH_SHORT).show();
}
});
}
}
}
在adapter中对于数据的操作就是对mDataSet这个List进行操作。但是对mDataSet进行修改以后我们还需要通知RecyclerView数据发生了改变,这就需要RecyclerView提供的以下几种方法
- adapter.notifyDataSetChanged();
- adapter.notifyItemInserted();
- adapter.notifyItemChanged();
- adapter.notifyItemMoved();
- adapter.notifyItemRemoved();
- adapter.notifyItemRangeChanged();
- adapter.notifyItemRangeInserted();
- adapter.notifyItemRangeRemoved();
其中第一种方法不会显示动画效果,它会直接将所有的 item 重新绘制。而后面七种方法会有相应的动画效果
在MainActivity.java中设置
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
MyAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter=new MyAdapter(this);
recyclerView=(RecyclerView) findViewById(R.id.recycler);
//设置LayoutManager为LinearLayoutManager
layoutManager= new LinearLayoutManager(this);
for(int i=0;i<100;i++){
ItemBean itemBean=new ItemBean();
itemBean.setText("第"+i+"项");
adapter.addItem(itemBean);
}
//设置LayoutManager和Adapter
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
}
从代码上可以看出RecyclerView必须设置LayoutManager和Adapter。Adapter前文已经讲过了,下面主要谈一下LayoutManager。
LayoutManager
LayoutManager主要用于定义RecyclerView的形式,系统提供了三种LayoutManager
- LinearLayoutManager 线性管理器,支持横向、纵向。
- GridLayoutManager 网格布局管理器
- StaggeredGridLayoutManager 瀑布流式布局管理器
上面的代码中我使用的就是 LinearLayoutManager
下拉刷新
- 利用SwipeRefreshLayout实现
- 在SwipeRefreshLayout.setOnRefreshListener里刷新数据
- 用SwipeRefreshLayout.setRefreshing(false)关闭刷新状态
refreshLayout=(SwipeRefreshLayout) findViewById(R.id.refresh);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
refreshData();
refreshLayout.setRefreshing(false);
}
});
private void refreshData(){
List<String> textList=new ArrayList<>();
for (int i = 1; i <= 20; i++) {
num++;
String s="第" + num + "项";
textList.add(s);
}
adapter.refreshItems(textList);
}
上拉加载
- 利用RecyclerView.addOnScrollListener实现
- 获取第一个可见的item的位置(firstVisibleItem)
- 获取可见的item的数量和总的item的数量(visibleItemCount和totalItemCount)
- 通过(totalItemCount - visibleItemCount) <= firstVisibleItem判断是否已经拉到了最后一页
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
private int totalItemCount;
private int firstVisibleItem;
private int visibleItemCount;
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
totalItemCount = layoutManager.getItemCount();
firstVisibleItem = layoutManager.findFirstVisibleItemPosition();
visibleItemCount = recyclerView.getChildCount();
if ( ((totalItemCount - visibleItemCount) <= firstVisibleItem)) {
onLoadMore();
}
}
private void onLoadMore() {
getData();
}
});
添加不同类型的Item
- 建立相应的布局文件
<!--item_header.xml-->
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground"
android:orientation="horizontal">
<ImageView
android:id="@+id/iv_image"
android:layout_width="match_parent"
android:layout_height="60dp"
android:gravity="center" />
</android.support.v7.widget.CardView>
接下来我们来改造以下刚才自定义的Adapter
- 给不同类型的Item建立相应的常量标识
public final static int ITEM_TYPE_HEADER = 0;
public final static int ITEM_TYPE_TEXT = 1;
- 重写getItemViewType方法
@Override
public int getItemViewType(int position) {
return position == 0 ? ITEM_TYPE_HEADER : ITEM_TYPE_TEXT;
}
- 建立相应的ViewHolder
public class TextViewHolder extends RecyclerView.ViewHolder {
TextView textView;
public TextViewHolder(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.tv_text);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(mContext, "第" + (getLayoutPosition() + 1) + "项被选中", Toast.LENGTH_SHORT).show();
}
});
}
}
public class HeaderViewHolder extends RecyclerView.ViewHolder{
ImageView imageView;
public HeaderViewHolder(View itemView) {
super(itemView);
imageView=(ImageView) itemView.findViewById(R.id.iv_image);
}
}
- 在onCreateViewHolder方法里根据viewType返回对应的ViewHolder
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
if (viewType == ITEM_TYPE_HEADER) {
itemView = LayoutInflater.from(mContext).inflate(R.layout.item_header, parent, false);
return new HeaderViewHolder(itemView);
} else {
itemView = LayoutInflater.from(mContext).inflate(R.layout.item_layout, parent, false);
return new TextViewHolder(itemView);
}
}
- 在onBindViewHolder方法里根据ViewHolder的类型执行相应操作
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof HeaderViewHolder)
((HeaderViewHolder) holder).imageView.setImageResource(R.drawable.logo);
else
((TextViewHolder) holder).textView.setText(mDataSet.get(position-1));
}
改造后的Adapter完整代码如下
public class MyAdapter extends RecyclerView.Adapter {
public final static int ITEM_TYPE_HEADER = 0;
public final static int ITEM_TYPE_TEXT = 1;
private List<String> mDataSet = new ArrayList<>();
private Context mContext;
public MyAdapter(Context context) {
mContext = context;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
if (viewType == ITEM_TYPE_HEADER) {
itemView = LayoutInflater.from(mContext).inflate(R.layout.item_header, parent, false);
return new HeaderViewHolder(itemView);
} else {
itemView = LayoutInflater.from(mContext).inflate(R.layout.item_layout, parent, false);
return new TextViewHolder(itemView);
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof HeaderViewHolder)
((HeaderViewHolder) holder).imageView.setImageResource(R.drawable.logo);
else
((TextViewHolder) holder).textView.setText(mDataSet.get(position-1));
}
@Override
public int getItemCount() {
return mDataSet.size();
}
public void refreshItems(List<String> items) {
mDataSet.clear();
mDataSet.addAll(items);
notifyDataSetChanged();
}
public void addItem(String item) {
mDataSet.add(item);
notifyDataSetChanged();
}
@Override
public int getItemViewType(int position) {
return position == 0 ? ITEM_TYPE_HEADER : ITEM_TYPE_TEXT;
}
public class TextViewHolder extends RecyclerView.ViewHolder {
TextView textView;
public TextViewHolder(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.tv_text);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(mContext, "第" + (getLayoutPosition() + 1) + "项被选中", Toast.LENGTH_SHORT).show();
}
});
}
}
public class HeaderViewHolder extends RecyclerView.ViewHolder{
ImageView imageView;
public HeaderViewHolder(View itemView) {
super(itemView);
imageView=(ImageView) itemView.findViewById(R.id.iv_image);
}
}
}
总结
通过上边的步骤,我们可以写出一个简单的RecyclerVIew。
上面demo的代码放在了github上:https://github.com/CodeChild/RecyclerViewDemo
如果有错误还请各位看官指正