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

相关内容

热门资讯

解迷透视!wpk德州局透视,w... 解迷透视!wpk德州局透视,wpk俱乐部是做什么的,切实是有辅助app(哔哩哔哩)1、德州局透视有没...
推荐透视!wepoker有脚本... 推荐透视!wepoker有脚本吗,wepoker养号规律,原来有辅助app(哔哩哔哩)1、进入游戏-...
分享透视!aapoker安装包... 分享透视!aapoker安装包怎么使用,aapoker辅助怎么用,真是一直都是有辅助插件(哔哩哔哩)...
普及透视!有哪些免费的wpk作... 普及透视!有哪些免费的wpk作比弊码,wpk透视怎么安装,一直真的是有辅助插件(哔哩哔哩)1、透视辅...
专业透视!hhpoker有没有... 专业透视!hhpoker有没有作比弊挂,hhpoker怎么破解,一直是有辅助插件(哔哩哔哩)该软件可...
普及透视!aapoker辅助工... 普及透视!aapoker辅助工具安全吗,aa poker透视软件,竟然存在有辅助技巧(哔哩哔哩)一、...
科普透视!wepoker免费脚... 科普透视!wepoker免费脚本咨询,如何下载wepoker安装包,一贯一直都是有辅助软件(哔哩哔哩...
开挂透视!德普之星怎么开辅助,... 开挂透视!德普之星怎么开辅助,德普之星辅助工具如何打开,一贯一直总是有辅助教程(哔哩哔哩)1、公共底...
开挂透视!hhpoker可以控... 开挂透视!hhpoker可以控制吗,wepoker软件安装包,好像存在有辅助方法(哔哩哔哩)1、该软...
必备透视!aapoker破解侠... 必备透视!aapoker破解侠是真的吗,aapoker怎么提高中牌率,都是存在有辅助教程(哔哩哔哩)...