RecyclerView分割线的设置,相对于ListView来说,要麻烦一些,但是RecyclerView的强大之处,ListView是不可比拟的,这也是大多数Android开发者选择RecyclerView的原因,当然,也有一小部分开发者因为分割线的问题,继续使用ListView。
其实,RecyclerView的分割线也没你想象的那么麻烦,直接使用官方提供的DividerItemDecoration即可,可惜的是,官方提供的ItemDecoration太少了(如下图所示)
下面使用DividerItemDecoration写个示例代码
1、在drawable文件夹下写个分割线的xml文件
inset_recyclerview_divider.xml
<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:insetLeft="10dp">
<!--android:insetLeft="10dp" 分割线距离左侧10dp-->
<shape>
<!--分割线的高度,横向的RecyclerView,这里设置宽度即可-->
<size android:height="1dp" />
<!--分割线的颜色-->
<solid android:color="@android:color/black" />
</shape>
</inset>
2、给RecyclerView设置分割线
/**
* 初始化RecyclerView
*/
private void initRecyclerView() {
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new BaseQuickAdapter<Citys.AllBean, BaseViewHolder>(R.layout.item_city) {
@Override
protected void convert(BaseViewHolder helper, Citys.AllBean item) {
}
@Override
public void onBindViewHolder(BaseViewHolder holder, int position) {
holder.setText(R.id.tv_name, allCitys.get(position).getName());
}
};
recyclerView.addItemDecoration(getRecyclerViewDivider(R.drawable.inset_recyclerview_divider));//设置分割线
recyclerView.setAdapter(adapter);
}
/**
* 获取分割线
*
* @param drawableId 分割线id
* @return
*/
public RecyclerView.ItemDecoration getRecyclerViewDivider(@DrawableRes int drawableId) {
DividerItemDecoration itemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
itemDecoration.setDrawable(getResources().getDrawable(drawableId));
return itemDecoration;
}
最后,简单分析下绘制垂直方向分割线的方法
/**
* 绘制垂直方向的分割线
* @param canvas
* @param parent
*/
private void drawVertical(Canvas canvas, RecyclerView parent) {
canvas.save();
final int left;
final int right;
//对应于布局中的clipToPadding属性,是否允许在padding区域绘制子View,true:不允许在padding区域绘制 false:允许在padding区域绘制子View
if (parent.getClipToPadding()) {
//不允许在padding区域绘制子View的left和right
left = parent.getPaddingLeft();
right = parent.getWidth() - parent.getPaddingRight();
//设置画布的显示区域(在布局文件中设置clipToPadding为true的关键在这里体现)
canvas.clipRect(left, parent.getPaddingTop(), right,
parent.getHeight() - parent.getPaddingBottom());
} else {
left = 0;
right = parent.getWidth();
}
//可见子View的数目
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
//获取装饰边界mBounds
parent.getDecoratedBoundsWithMargins(child, mBounds);
final int bottom = mBounds.bottom + Math.round(ViewCompat.getTranslationY(child));
final int top = bottom - mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);//设置分割线的位置
mDivider.draw(canvas);//绘制分割线
}
canvas.restore();
}
推荐下RecyclerView分割线开源库:https://github.com/hiphonezhu/RecyclerView-FlexibleDivider