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

相关内容

热门资讯

专业讨论!博雅棋牌辅助器,山西... 专业讨论!博雅棋牌辅助器,山西扣点工具(原来真的有挂)1.博雅棋牌辅助器 选牌创建新账号,点击进入游...
今日头条!广东闲来辅助工具,随... 今日头条!广东闲来辅助工具,随意玩脚本辅助工具透视(确实是有挂)1、进入到随意玩脚本辅助工具透视是否...
发现一款!来物局怎么开挂,微信... 发现一款!来物局怎么开挂,微信小程序功夫川码辅助(果然真的是有挂)1、超多福利:超高返利,海量正版游...
攻略讲解!四川途游麻将外挂,哈... 攻略讲解!四川途游麻将外挂,哈局八张挂辅助(竟然是有挂)小薇(辅助器软件下载)致您一封信;亲爱四川途...
分享一款!西兵互娱辅助插件ap... 分享一款!西兵互娱辅助插件app,邯郸胡乐挂辅助(真是存在有挂)进入游戏-大厅左侧-新手福利-激活码...
一分钟了解!福建兄弟13水破解... 一分钟了解!福建兄弟13水破解版插件,丽水都莱脚本辅助(本来是真的有挂)一分钟了解!福建兄弟13水破...
必备攻略!雀神挂件价格辅助开挂... 必备攻略!雀神挂件价格辅助开挂,四川游戏家园破解(确实是有挂)1、雀神挂件价格辅助开挂透视辅助软件激...
重大通报!西兵互娱辅助插件ap... 重大通报!西兵互娱辅助插件app,海螺众娱辅助(切实存在有挂)该软件可以轻松地帮助玩家将西兵互娱辅助...
总算了解!川娱竞技血战辅助器,... 总算了解!川娱竞技血战辅助器,微信小程序里的微乐可以开挂吗(都是真的是有挂)1)微信小程序里的微乐可...
我来教大家!陕麻圈辅助器透视开... 我来教大家!陕麻圈辅助器透视开挂,赣湘互娱怎么下载辅助(果然真的有挂)1、陕麻圈辅助器透视开挂破解器...