android开发杂识RecyclerView研究内容Android技术知识

RecyclerView系列之二:添加分隔线

2017-04-17  本文已影响1579人  滴滴滴9527

在上一篇RecyclerView系列之一:实现常见的ListView效果简单介绍了使用RecyclerView如何实现ListView的效果,但是我们也发现了,效果图中没有分隔线,今天将介绍如何为RecyclerView添加分隔线.

一、如何添加分隔线

嗯,首先有两种比较low的方式:
1、为item布局设置一个背景色,再为item根标签设置一个margin或者padding,这样就形成了分隔线的效果.
2、在Item布局文件最后加一条横线,为它设置一个背景色,形成分隔线的效果.

然后就是正式的写法了:
3、RecyclerView中可以通过addItemDecoration()方法添加分割线, 该方法的参数为RecyclerView.ItemDecoration,该类为抽象类,官方目前只提供了一个实现类DividerItemDecoration.

public class MainActivity extends AppCompatActivity {

    private RecyclerView mRecyclerView;
    private LinearLayoutManager layoutManager;
    private MainAdapter mAdapter;
    private List<String> mDatas;
    private DividerItemDecoration mDivider;//分隔线

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initData();
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(layoutManager);

        //初始化分隔线、添加分隔线
        mDivider = new DividerItemDecoration(this,DividerItemDecoration.VERTICAL);
        mRecyclerView.addItemDecoration(mDivider);

        mAdapter = new MainAdapter(this,mDatas);
        mRecyclerView.setAdapter(mAdapter);
    }

    private void initData() {
        mDatas = new ArrayList<>();
        for (int i = 'A'; i < 'Z'; i++) {
            mDatas.add("" + (char) i);
        }
    }
}

现在我们再来看一下效果图:


看起来还行,但是万一这种效果不是我们需要的怎么办?所以我们应该知道RecyclerView是如何画出分隔线的

二、抽象类RecyclerView.ItemDecoration源码

 public static abstract class ItemDecoration {
       
        public void onDraw(Canvas c, RecyclerView parent, State state) {
            onDraw(c, parent);
        }
        @Deprecated
        public void onDraw(Canvas c, RecyclerView parent) {
        }

        public void onDrawOver(Canvas c, RecyclerView parent, State state) {
            onDrawOver(c, parent);
        }
        @Deprecated
        public void onDrawOver(Canvas c, RecyclerView parent) {
        }


        @Deprecated
        public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
            outRect.set(0, 0, 0, 0);
        }
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, State state) {
            getItemOffsets(outRect, ((LayoutParams) view.getLayoutParams()).getViewLayoutPosition(),
                    parent);
        }
    }

当我们调用addItemDecoration()方法添加decoration的时候,RecyclerView就会调用该类的onDraw方法去绘制分隔线,也就是说:分隔线是绘制出来的. 下面来了解分隔线是如何绘制出来的.

三、理解分隔线是如何绘制的

系统默认实现类DividerItemDecoration涉及到clipToPadding属性、画布的裁剪一些知识,不太容易理解,也不方便修改,这里介绍网上通用的实现.
首先要理解一个概念:分隔线本质是一个矩形,这个“线”是有长度和宽度的.

/**
* 默认分隔线实现类只支持布局管理器为 LinearLayoutManager
*/
public class CommonItemDecoration extends RecyclerView.ItemDecoration {
    public static final int HORIZONTAL = LinearLayout.HORIZONTAL;
    public static final int VERTICAL = LinearLayout.VERTICAL;

    //使用系统主题中的R.attr.listDivider作为Item间的分割线
    private static final int[] ATTRS = new int[]{ android.R.attr.listDivider};

    private Drawable mDivider;

    private int mOrientation;//布局方向,决定绘制水平分隔线还是竖直分隔线

    private final Rect mBounds = new Rect();


    public CommonItemDecoration (Context context, int orientation) {
        final TypedArray a = context.obtainStyledAttributes(ATTRS);
        mDivider = a.getDrawable(0);
        a.recycle();
        setOrientation(orientation);
    }

    public void setOrientation(int orientation) {
        if (orientation != HORIZONTAL && orientation != VERTICAL) {
            throw new IllegalArgumentException(
                    "Invalid orientation. It should be either HORIZONTAL or VERTICAL");
        }
        mOrientation = orientation;
    }

    /**
     * 一个app中分隔线不可能完全一样,你可以通过这个方法传递一个Drawable 对象来定制分隔线
     */
    public void setDrawable(@NonNull Drawable drawable) {
        if (drawable == null) {
            throw new IllegalArgumentException("Drawable cannot be null.");
        }
        mDivider = drawable;
    }

    /**
     * 画分隔线
     */
    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        if (parent.getLayoutManager() == null) {
            return;
        }
        if (mOrientation == VERTICAL) {
            drawVertical(c, parent);
        } else {
            drawHorizontal(c, parent);
        }
    }

    /**
     * 在LinearLayoutManager方向为Vertical时,画分隔线
     */
    public void drawVertical(Canvas canvas, RecyclerView parent) {
        final int left = parent.getPaddingLeft();//★分隔线的左边 = paddingLeft值
        final int right = parent.getWidth() - parent.getPaddingRight();//★分隔线的右边 = RecyclerView 宽度-paddingRight值
//分隔线不在RecyclerView的padding那一部分绘制

        final int childCount = parent.getChildCount();//★分隔线数量=item数量
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);//确定是第几个item
            final RecyclerView.LayoutParams params =(RecyclerView.LayoutParams) child.getLayoutParams();
            final int top = child.getBottom() + params.bottomMargin;//★分隔线的上边 = item的底部 + item根标签的bottomMargin值 
            final int bottom = top + mDivider.getIntrinsicHeight();//★分隔线的下边 = 分隔线的上边 + 分隔线本身高度
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(canvas);
        }
    }


    /**
     * 在LinearLayoutManager方向为Horizontal时,画分隔线
     *      理解了上面drawVertical()方法这个方法也就理解了
     */
    public void drawHorizontal(Canvas canvas, 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 params = (RecyclerView.LayoutParams) child.getLayoutParams();
            final int left = child.getRight() + params.rightMargin;
            final int right = left + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(canvas);
        }
    }

    /**
     *  获取Item偏移量
     *    此方法是为每个Item四周预留出空间,从而让分隔线的绘制在预留的空间内
     */
   @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
            RecyclerView.State state) {
        if (mOrientation == VERTICAL) {//竖直方向的分隔线:item向下偏移一个分隔线的高度
            outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
        } else {//水平方向的分隔线:item向右偏移一个分隔线的宽度
            outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
        }
    }
}

四、更改分隔线的样式

DividerItemDecoration画的分割线是读取系统的属性android.R.attr.listDivider,使用系统的listDivider好处就是就是方便我们去随意的分隔线的样式

1、找到res/values/styles.xml,在其中声明android:listDivider属性,然后使用我们自己的样式
<resources>
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="android:listDivider">@drawable/my_divider</item>
    </style>
</resources>
2、在res/drawable目录下声明我们自己的样式my_divider.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <gradient
        android:centerColor="#ff00ff"
        android:endColor="#00ff00"
        android:startColor="#0000ff"
        android:type="linear" />
    <size android:height="4dp"/>
</shape>

再来看一下效果图


3、当然,这样一修改就改变整个app中的分隔线效果了,如果只是想改变某个列表中的分隔线效果,完全可以通过分隔线的setDrawable方法来修改
mDivider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
mDivider.setDrawable(getResources().getDrawable(R.drawable.my_divider));
mRecyclerView.addItemDecoration(mDivider);

这样一来,不同的列表就可以使用不同的分隔线效果了.

上一篇下一篇

猜你喜欢

热点阅读