RecyclerView.ItemDecoration实现占位Item
一、为什么需要占位Item
神马笔记的移动功能使用了树形结构的RecyclerView,在初始状态下只有一个根Item,点击Item后会展开子目录内容,为了增加指示性以及丰富界面,因此需要在界面中增加占位Item。
二、实现效果
空白部分使用了占位Item,增加了指示性,丰富了界面。
注:原始图片为720 x 1440,缩放为320 x 640后,空白位置的分割线显示不是特别明显。
下载安装【whatsnote_lastest.apk】能更明显看到效果。
三、实现原理
使用RecyclerView.ItemDecoration
绘制空白部分的分割线产生占位Item的效果。
关键过程:
- 获取最后一个Item的位置,从最后一个Item位置开始绘制分割线
- 获取Item的高度,树形结构中总有一个根节点,获取任意一个Item的高度即可
- 计算绘制的个数,根据RecyclerView的高度及以上2个参数,即可计算出个数
四、完整代码
package club.andnext.recyclerview.decoration;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.view.View;
import androidx.recyclerview.widget.RecyclerView;
import club.andnext.recyclerview.R;
public class PlaceholderDecoration extends RecyclerView.ItemDecoration {
Drawable divider;
int margin;
Rect bounds;
public PlaceholderDecoration(Context context) {
this.divider = context.getDrawable(R.drawable.anc_shape_list_divider);
this.bounds = new Rect();
}
public PlaceholderDecoration setMargin(int value) {
this.margin = value;
return this;
}
@Override
public void onDraw(Canvas canvas, RecyclerView parent, RecyclerView.State state) {
if (parent.getLayoutManager() == null || divider == null) {
return;
}
canvas.save();
final int left;
final int right;
//noinspection AndroidLintNewApi - NewApi lint fails to handle overrides.
if (parent.getClipToPadding()) {
left = parent.getPaddingLeft();
right = parent.getWidth() - parent.getPaddingRight();
canvas.clipRect(left, parent.getPaddingTop(), right,
parent.getHeight() - parent.getPaddingBottom());
} else {
left = 0;
right = parent.getWidth();
}
int x = left + margin;
int y = 0;
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
parent.getDecoratedBoundsWithMargins(child, bounds);
final int bottom = bounds.bottom;
y = (y < bottom)? bottom: y;
}
if (childCount != 0) {
int height = parent.getChildAt(0).getHeight();
int count = (parent.getHeight() - y) / height;
y += height;
for (int i = 0; i < count; i++) {
divider.setBounds(x, y, right, y + divider.getIntrinsicHeight());
divider.draw(canvas);
y += height;
}
}
canvas.restore();
}
}
五、核心代码
- 计算bottom位置
注意:这里不能直接取最后一个Item的bottom。 因为是RecyclerView,最后一个Item在位置上不一定是最后一个,并且还存在被重用的情况。
正确的做法是遍历所有的Item,计算出最大bottom位置。
int y = 0;
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
parent.getDecoratedBoundsWithMargins(child, bounds);
final int bottom = bounds.bottom;
y = (y < bottom)? bottom: y;
}
- 绘制分割线
根据RecyclerView的高度及bottom计算出绘制个数,循环绘制分割线即可。
if (childCount != 0) {
int height = parent.getChildAt(0).getHeight();
int count = (parent.getHeight() - y) / height;
y += height;
for (int i = 0; i < count; i++) {
divider.setBounds(x, y, right, y + divider.getIntrinsicHeight());
divider.draw(canvas);
y += height;
}
}
六、下载地址
神马笔记最新版本:【whatsnote_lastest.apk】