Android-Custom View要严格保持在布局的自定义边界内
创始人
2024-08-19 17:00:37
0

要实现Android-Custom View严格保持在布局的自定义边界内,可以使用以下解决方法:

  1. 在Custom View的构造函数中,使用setWillNotDraw(false)来确保Custom View会被绘制。
public class CustomView extends View {
    public CustomView(Context context) {
        super(context);
        setWillNotDraw(false);
    }
}
  1. 在Custom View的onMeasure()方法中,根据布局的宽度和高度来确定Custom View的实际大小,并确保它不超出布局的边界。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int desiredWidth = ...; // 自定义宽度
    int desiredHeight = ...; // 自定义高度

    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);

    int width, height;

    if (widthMode == MeasureSpec.EXACTLY) {
        width = widthSize;
    } else if (widthMode == MeasureSpec.AT_MOST) {
        width = Math.min(desiredWidth, widthSize);
    } else {
        width = desiredWidth;
    }

    if (heightMode == MeasureSpec.EXACTLY) {
        height = heightSize;
    } else if (heightMode == MeasureSpec.AT_MOST) {
        height = Math.min(desiredHeight, heightSize);
    } else {
        height = desiredHeight;
    }

    setMeasuredDimension(width, height);
}
  1. 在Custom View的onLayout()方法中,根据布局的边界,计算Custom View的实际位置。
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    int width = right - left;
    int height = bottom - top;

    // 计算Custom View的实际位置
    int customViewLeft = ...;
    int customViewTop = ...;
    int customViewRight = customViewLeft + width;
    int customViewBottom = customViewTop + height;

    layout(customViewLeft, customViewTop, customViewRight, customViewBottom);
}
  1. 在Custom View的onDraw()方法中,绘制Custom View的内容。
@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    // 在Custom View内部绘制内容
    // ...
}

通过以上步骤,Custom View就能够严格保持在布局的自定义边界内了。

相关内容

热门资讯

揭秘真相!h5大厅反杀,佛手在... 揭秘真相!h5大厅反杀,佛手在线大菠萝辅助,详细器(有挂详细)揭秘真相!h5大厅反杀,佛手在线大菠萝...
记者发布!广东雀神祈福辅助器,... 记者发布!广东雀神祈福辅助器,新道游正版作弊微信辅助,详细软件(真是有挂)1、新道游正版作弊微信辅助...
总算明白!九游辅助工具,微信小... 总算明白!九游辅助工具,微信小程序蜀山四川辅助器,详细app(真的有挂)亲,关键说明,微信小程序蜀山...
最新通报!老友麻将辅助器,琼戏... 最新通报!老友麻将辅助器,琼戏互娱破解版,详细挂(有挂总结)1、让任何用户在无需琼戏互娱破解版安装教...
推荐一款!哈局八张辅助,微信小... 推荐一款!哈局八张辅助,微信小程序辅助器免费下载,详细攻略(今日头条)在进入微信小程序辅助器免费下载...
总算了解!微信小程序辅助器破解... 总算了解!微信小程序辅助器破解版,顺兴茶楼开挂,详细攻略(有挂方式)微信小程序辅助器破解版是不是有人...
一分钟揭秘!福建天天开心王国辅... 一分钟揭秘!福建天天开心王国辅助,潮友会app下载官方辅助器,详细攻略(有挂细节)亲,关键说明,潮友...
六分钟了解!jj斗地主外开挂,... 六分钟了解!jj斗地主外开挂,蜀渝牌乐汇辅助,详细软件(有挂细节)1、在蜀渝牌乐汇辅助插件功能辅助器...
三分钟了解!蘑菇云辅助脚本,皮... 三分钟了解!蘑菇云辅助脚本,皮皮胡子跑辅助,详细方法(有挂攻略)1、皮皮胡子跑辅助透视辅助软件激活码...
科技通报!黑科技微乐小程序辅助... 科技通报!黑科技微乐小程序辅助器免费,随意玩辅助器视频有挂,详细技巧(有挂工具)1)黑科技微乐小程序...