序言
为了研究瀑布流布局中的布局规律和 StaggeredGridLayoutManager.LayoutParams中的spanIndex的关系。需要把这些内容打印出来,但是不如直接显示在item方便。于是写了一个drawable来实现
效果
前面实现的是position 后面是spanIndex
使用
DebugDrawable
把下面的drawable引入
package com.trs.baseapp.news.list.ui.binder;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.trs.common.util.AppUtil;
/**
* <pre>
* Created by zhuguohui
* Date: 2024/8/29
* Time: 16:56
* Desc:
* </pre>
*/
public class DebugDrawable extends Drawable {
private final Paint bgPaint;
private final int padding;
String debugInfo;
Paint paint;
public DebugDrawable(String debugInfo) {
this.debugInfo = debugInfo;
paint = new Paint();
paint.setColor(Color.RED);
paint.setTextSize(AppUtil.dip2px(16));
bgPaint = new Paint();
bgPaint.setColor(Color.YELLOW);
padding = 10;
}
@Override
public void draw(@NonNull Canvas canvas) {
canvas.drawColor(Color.parseColor("#33000000"));
float textWidth = paint.measureText(debugInfo);
int textHeight = (int) paint.getTextSize();
int width = getBounds().width();
int x = (int) (width / 2 - textWidth / 2);
int y = getBounds().height() / 2 + textHeight / 2;
canvas.drawRect(x -padding, y - textHeight - padding, x + textWidth + padding, y + padding, bgPaint);
canvas.drawText(debugInfo, x, y, paint);
}
@Override
public void setAlpha(int i) {
}
@Override
public void setColorFilter(@Nullable ColorFilter colorFilter) {
}
@Override
public int getOpacity() {
return PixelFormat.OPAQUE;
}
}
示例
把drawable作为item的前景,把要显示的信息,通过构造函数传入即可
@Override
protected void onBindViewHolderByChild(BaseViewHolder holder, NewsUI ui) {
StaggeredGridLayoutManager.LayoutParams layoutParams = (StaggeredGridLayoutManager.LayoutParams) holder.itemView.getLayoutParams();
Log.i("zzz", "onBindViewHolderByChild: lp="+layoutParams);
holder.itemView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int spanIndex = layoutParams.getSpanIndex();
int adapterPosition = holder.getAdapterPosition();
holder.itemView.setForeground(new DebugDrawable(adapterPosition+":"+spanIndex));
}
});
}