可以显示调试信息的Drawable

序言

为了研究瀑布流布局中的布局规律和 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));
            }
        });

    }
  • 7
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值