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)约局吧德州有挂吗辅助插件:进...
解迷透视!hhpoker辅助挂... 解迷透视!hhpoker辅助挂是真的吗,智星德州可以透视吗,方案教程(有挂方法)-哔哩哔哩1、完成h...
详情透视!hh poker辅助... 详情透视!hh poker辅助器先试用,红龙poker辅助器免费观看,绝活教程(有挂攻略)-哔哩哔哩...
详情透视!大菠萝免费辅助!好像... 详情透视!大菠萝免费辅助!好像是真的有辅助app(真的有挂)-哔哩哔哩1、大菠萝免费辅助公共底牌简单...
解谜透视!哈糖大菠萝有没有挂!... 解谜透视!哈糖大菠萝有没有挂!原来存在有辅助技巧(有挂助手)-哔哩哔哩哈糖大菠萝有没有挂是不是有人用...
辅助透视!pokemmo免费脚... 辅助透视!pokemmo免费脚本,安装不了wepoker,方案教程(有挂总结)-哔哩哔哩安装不了we...
有挂透视!聚星ai辅助工具下载... 有挂透视!聚星ai辅助工具下载!竟然真的是有辅助软件(竟然有挂)-哔哩哔哩1、让任何用户在无需聚星a...
解迷透视!hardrock透视... 解迷透视!hardrock透视工具,wepoker透视苹果系统,总结教程(真是有挂)-哔哩哔哩在进入...