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就能够严格保持在布局的自定义边界内了。

相关内容

热门资讯

正版外挂开开互动外挂多功能AI... 正版外挂开开互动外挂多功能AI插件,开开互动确实是真的有外挂插件1、正版外挂开开互动外挂多功能AI插...
WPK靠谱教材!扑克之星辅助,... WPK靠谱教材!扑克之星辅助,智星菠萝德州ai多功能辅助app1、下载好扑克之星辅助透视辅助下载之后...
正版透视挂赤峰祥云麻将透视挂多... 正版透视挂赤峰祥云麻将透视挂多功能AI插件,赤峰祥云麻将竟然有透视挂插件该软件可以轻松地帮助玩家将赤...
WPK辅助绝活!wpk软件是正... WPK辅助绝活!wpk软件是正规的吗,微扑克ai多功能透视神器暗藏猫腻,小编详细说明wpk软件是正规...
正版透视器欢乐途游麻将透视器多... 正版透视器欢乐途游麻将透视器多功能AIapp,欢乐途游麻将都是是有透视器app1、完成欢乐途游麻将有...
WPK软件手筋!约局吧开挂神器... WPK软件手筋!约局吧开挂神器是真的吗,红龙扑克ai多功能辅助器神器WPK软件手筋!约局吧开挂神器是...
正版透视挂天狐游戏透视挂多功能... 正版透视挂天狐游戏透视挂多功能AI插件,天狐游戏确实真的是有透视挂插件小薇(辅助器软件下载)致您一封...
WPK作弊项目!德扑之星透视辅... WPK作弊项目!德扑之星透视辅助软件,红龙扑克ai多功能辅助攻略1、不需要AI权限,帮助你快速的进行...
正版辅助湘竞技辅助多功能AI攻... 正版辅助湘竞技辅助多功能AI攻略,湘竞技原来是真的有辅助攻略1、湘竞技免费辅助多个强度级别选择2、湘...
WPK透视版资料!德扑之星辅助... WPK透视版资料!德扑之星辅助正版,wpkai多功能透视方法1、德扑之星辅助正版公共底牌简单,德扑之...