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

相关内容

热门资讯

普及透视!哈糖大菠萝助手,微乐... 普及透视!哈糖大菠萝助手,微乐自建房辅助工具,指引教程(确实有挂)-哔哩哔哩一、哈糖大菠萝助手游戏安...
了解透视!wepokerplu... 了解透视!wepokerplus万能挂,微乐自建房辅助工具2025在哪,积累教程(存在有挂)-哔哩哔...
分享透视!拱趴大菠萝机器人,微... 分享透视!拱趴大菠萝机器人,微乐家乡自建房辅助app,练习教程(有挂总结)-哔哩哔哩1、任何拱趴大菠...
有挂透视!大菠萝789辅助器下... 有挂透视!大菠萝789辅助器下载,微乐小程序插件免费,讲义教程(有挂透明挂)-哔哩哔哩1、许多玩家不...
总结透视!werplan辅助软... 总结透视!werplan辅助软件,微乐小程序有脚本吗,机巧教程(有挂总结)-哔哩哔哩1、上手简单,内...
开挂透视!wpk刷入池率脚本,... 开挂透视!wpk刷入池率脚本,微信小程序微乐辅助器免费版v2.0,模板教程(有挂透明挂)-哔哩哔哩1...
有挂透视!aapoker公共底... 有挂透视!aapoker公共底牌,微乐智能辅助软件是真的吗,策略教程(有挂分析)-哔哩哔哩所有人都在...
有挂透视!hhpoker软件可... 有挂透视!hhpoker软件可以玩吗,微信小程序微乐为什么老输,手筋教程(真的有挂)-哔哩哔哩1、每...
科普透视!wepoker有没有... 科普透视!wepoker有没有辅助,微乐自建房辅助免费入口,模块教程(有挂解密)-哔哩哔哩1、每一步...
分享透视!大菠萝手游辅助,收i... 分享透视!大菠萝手游辅助,收i就微乐小程序游戏破解器,手段教程(有人有挂)-哔哩哔哩1、大菠萝手游辅...