Android开发——RecyclerView的使用(二)
Android开发——RecyclerView的使用(三)
使用RecyclerView 加载大量数据集已经有一端时间了,但是一直没有对RecyclerView 总结记录过。今天再一次使用到RecyclerView ,就在这里做一次详细的总结。
引用类
使用RecyclerView 首先需要引入类。在build.gradle文件中引入该类。
compile 'com.android.support:recyclerview-v7:23.4.0'
AS 3.0以后的是:
implementation 'com.android.support:recyclerview-v7:27.1.1'
RecyclerView 的优缺点:
优点:新控件RecyclerView,提供了一种插拔式的体验,高度的解耦,异常的灵活,通过设置它提供的不同LayoutManager,ItemDecoration , ItemAnimator 实现 ListView,GirdView,瀑布流等效果。
缺点: Item的点击、长按事件,需要自己写。
LayoutManager:布局管理器
RecyclerView和ListView、GridView不同的一点就是需要自己现在要添加的布局管理器。RecyclerView的布局管理器是一个抽象类,系统提供了三个实现类:
- LinearLayoutManager 线性布局管理器,支持横向或纵向选择。
- GridLayoutManager 网格布局管理器
- StaggeredGridLayoutManager 瀑布流 布局管理器
如果想用 RecyclerView 来实现自定义效果,则应该去继承实现 LayoutManager,并重写相应的方法。
RecyclerView的基本使用
RecyclerView的使用对比ListView和GridView就比较熟悉了。总的来说有以下几个步骤:
1、类引用
2、初始化控件
3、设置布局管理器
4、设置adapter
5、添加分割线
6、设置Item的增删动画
7、添加Item的点击、长按事件
现在我们实现一次RecyclerView加载数据源的过程。
LinearLayoutManager —— 线性布局管理器
使用RecyclerView实现类似ListView的线性布局,过程很简单,Activity源码如下:
package com.demo.recyclerview;
import android.graphics.Canvas;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import com.demo.BaseActivity;
import com.demo.R;
import java.util.ArrayList;
import java.util.List;
public class DemoActivity extends BaseActivity {
private RecyclerView mRecyclerView;
private List<BaseEntity> mEntityList;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo);
// 初始化控件
mRecyclerView = findViewById(R.id.demo_recycler_view);
initData();
initRecyclerView();
}
private void initData(){
mEntityList = new ArrayList<>();
for(int i = 'A'; i <= 'z'; i++){
BaseEntity entity = new BaseEntity();
entity.setText("" + (char)i);
mEntityList.add(entity);
}
}
/**
* 初始化RecyclerView
*/
private void initRecyclerView(){
// 定义一个线性布局管理器
LinearLayoutManager manager = new LinearLayoutManager(this);
// 设置布局管理器
mRecyclerView.setLayoutManager(manager);
// 设置adapter
DemoAdapter adapter = new DemoAdapter(DemoActivity.this, mEntityList);
mRecyclerView.setAdapter(adapter);
}
}
Adapter源码如下:
package com.demo.recyclerview;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.demo.R;
import java.util.List;
public class DemoAdapter extends RecyclerView.Adapter {
private Context mContext;
private List<BaseEntity> mEntityList;
public DemoAdapter (Context context, List<BaseEntity> entityList){
this.mContext = context;
this.mEntityList = entityList;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_demo, parent, false);
return new DemoViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
BaseEntity entity = mEntityList.get(position);
((DemoViewHolder)holder).mText.setText(entity.getText());
}
@Override
public int getItemCount() {
return mEntityList.size();
}
private class DemoViewHolder extends RecyclerView.ViewHolder{
private TextView mText;
public DemoViewHolder(View itemView) {
super(itemView);
mText = (TextView) itemView.findViewById(R.id.item_text);
}
}
}
如此一个简单的类似ListView的页面就完成了。效果如图:
界面效果不仅有点单调,而且还不能点击、长按,这些不急,我们一步一步来添加。
ItemDecoration——分割线
首先我们先来添加分割线,因为没有分割线的界面显得好丑。
我们通过mRecyclerView.addItemDecoration(RecyclerView.ItemDecoration itemDecoration)
方法添加分割线,ItemDecoration类为抽象类,目前官方没有提供默认的实现类。
先看ItemDecoration源码
public static abstract class ItemDecoration {
public void onDraw(Canvas c, RecyclerView parent, State state) {
onDraw(c, parent);
}
public void onDrawOver(Canvas c, RecyclerView parent, State state) {
onDrawOver(c, parent);
}
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, State state) {
getItemOffsets(outRect, ((LayoutParams) view.getLayoutParams()).getViewLayoutPosition(),
parent);
}
@Deprecated
public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
outRect.set(0, 0, 0, 0);
}
当我们调mRecyclerView.addItemDecoration()方法添加decoration的时候,RecyclerView在绘制的时候,去会绘制decorator,即调用该类的onDraw和onDrawOver方法,三个方法介绍:
- onDraw 方法先于 drawChildren
- onDrawOver 在 drawChildren之后,一般我们选择复写其中一个即可。
- getItemOffsets 可以通过 outRect.set() 为每个Item设置一定的偏移量,主要用于绘制Decorator。
下面我们自己来写一个分割线的实现类。
package com.demo.recyclerview;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
public class LinearItemDecoration extends RecyclerView.ItemDecoration {
private static final String TAG = "LinearItemDecoration";
private static final int[] ATTRS = new int[]{android.R.attr.listDivider};
public static final int ORIENTATION_HORIZONTAL = LinearLayoutManager.HORIZONTAL;
public static final int ORIENTATION_VERTICAL = LinearLayoutManager.VERTICAL;
private Drawable mDrawable;
private int mOrientation;
public LinearItemDecoration(Context context, int orientation){
final TypedArray typedArray = context.obtainStyledAttributes(ATTRS);
mDrawable = typedArray.getDrawable(0);
typedArray.recycle();
setOrientation(orientation);
}
public void setOrientation(int orientation) {
if(orientation != ORIENTATION_HORIZONTAL && orientation != ORIENTATION_VERTICAL){
this.mOrientation = ORIENTATION_VERTICAL;
}
this.mOrientation = orientation;
}
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
if(mOrientation == ORIENTATION_HORIZONTAL){
drawHorizontal(c, parent);
} else {
drawVertical(c, parent);
}
}
private void drawHorizontal(Canvas c, RecyclerView parent){
final int top = parent.getPaddingTop();
final int bottom = parent.getHeight() - parent.getPaddingBottom();
final int childCount = parent.getChildCount();
for(int i = 0; i < childCount; i++){
final View child = parent.getChildAt(i);
final RecyclerView.LayoutParams layoutManager = (RecyclerView.LayoutParams) child.getLayoutParams();
final int left = child.getRight() + layoutManager.rightMargin;
final int right = left + mDrawable.getIntrinsicHeight();
mDrawable.setBounds(left, top, right, bottom);
mDrawable.draw(c);
}
}
private void drawVertical(Canvas c, RecyclerView parent){
final int left = parent.getPaddingLeft();
final int right = parent.getWidth() - parent.getPaddingRight();
final int childCount = parent.getChildCount();
for(int i = 0; i < childCount; i++){
final View child = parent.getChildAt(i);
final RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
final int top = child.getBottom() + layoutParams.bottomMargin;
final int bottom = top + mDrawable.getIntrinsicHeight();
mDrawable.setBounds(left, top, right, bottom);
mDrawable.draw(c);
}
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
if(mOrientation == ORIENTATION_HORIZONTAL){
outRect.set(0, 0, mDrawable.getIntrinsicWidth(), 0);
} else {
outRect.set(0, 0, 0, mDrawable.getIntrinsicHeight());
}
}
}
在初始化RecyclerView时添加分割线:
// 添加分割线
mRecyclerView.addItemDecoration(new LinearItemDecoration(DemoActivity.this, LinearLayoutManager.VERTICAL));
然后分割线效果就出来了。如下图:
上面的分割线是系统默认的,然后我们自定义分割线的效果。分割线实现类里可以看到通过读取系统主题中的 Android.R.attr.listDivider作为 Item 间的分割线,也就是说我们可以通过改变listDivider的属性值来改变分割线样式。
在主题样式文件styles.xml里,添加如下代码
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:listDivider">@drawable/bg_list_divider</item>
</style>
然后就可以自定义Drawable图片bg_list_divider.xml来设置自己的分割线样式了。我自己添加的分割线如下图:
点击和长按事件监听
前面说过系统没有提供点击和长按的事件监听,需要我们自己添加。添加方式是通过adapter自己提供回调。
public interface OnItemClickLitener{
void onItemClick(View view, int position);
void onItemLongClick(View view , int position);
}
private OnItemClickLitener mOnItemClickLitener;
public void setOnItemClickLitener(OnItemClickLitener onItemClickLitener){
this.mOnItemClickLitener = onItemClickLitener;
}
@Override
public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, int position) {
BaseEntity entity = mEntityList.get(position);
((DemoViewHolder)holder).mText.setText(entity.getText());
if(mOnItemClickLitener != null){
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int pos = holder.getLayoutPosition();
mOnItemClickLitener.onItemClick(holder.itemView, pos);
}
});
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
int pos = holder.getLayoutPosition();
mOnItemClickLitener.onItemLongClick(holder.itemView, pos);
return false;
}
});
}
}
在Activity里监听点击或长按事件
adapter.setOnItemClickLitener(new DemoAdapter.OnItemClickLitener() {
@Override
public void onItemClick(View view, int position) {
Toast.makeText(DemoActivity.this, "单击了" + mEntityList.get(position).getText(), Toast.LENGTH_SHORT).show();
}
@Override
public void onItemLongClick(View view, int position) {
Toast.makeText(DemoActivity.this, "长按了" + mEntityList.get(position).getText(), Toast.LENGTH_SHORT).show();
}
});
点击和长按的效果图就不贴出来了。
到这里RecyclerView实现线性布局基本的使用以及介绍完了。