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

相关内容

热门资讯

2026版辅助挂!牵手游戏ap... 2026版辅助挂!牵手游戏app辅助器,心悦踢辅助软件-其实真的是有辅助神器(哔哩哔哩)1、完成牵手...
反观!金州水鱼脚本,永盛联盟辅... 反观!金州水鱼脚本,永盛联盟辅助脚本-其实真的是有辅助插件(哔哩哔哩)1、下载好永盛联盟辅助脚本脚本...
方法辅助挂!新漫游免费辅助器,... 方法辅助挂!新漫游免费辅助器,新海贝之城脚本-竟然存在有辅助脚本(哔哩哔哩)在进入新漫游免费辅助器软...
代打辅助挂!微信老铁13水辅助... 代打辅助挂!微信老铁13水辅助,仙神互娱辅助-果然确实有辅助器(哔哩哔哩)1、任何微信老铁13水辅助...
黑科技辅助挂!乐酷副厅外卖辅助... 黑科技辅助挂!乐酷副厅外卖辅助,掌中乐游戏辅助工具-好像真的是有辅助工具(哔哩哔哩)1、下载好掌中乐...
今日!桃乐甘肃麻将辅助器,天天... 今日!桃乐甘肃麻将辅助器,天天福建十三兵修改器-一贯存在有辅助挂(哔哩哔哩)1、任何天天福建十三兵修...
透视免费!新九天作必弊系统,赣... 透视免费!新九天作必弊系统,赣湘互娱辅助-切实是真的有辅助神器(哔哩哔哩)1、玩家可以在新九天作必弊...
截至目前!金虎爷辅助器,新51... 截至目前!金虎爷辅助器,新518互游插件下载-真是是真的有辅助神器(哔哩哔哩)1、下载好新518互游...
截至发稿!蜀山四川辅助脚本,福... 截至发稿!蜀山四川辅助脚本,福建天天开心辅助工具下载-真是真的是有辅助app(哔哩哔哩)1、上手简单...
随着!杭州都莱大菠萝买了挂有用... 随着!杭州都莱大菠萝买了挂有用吗,小唐家乐园辅助-真是是有辅助软件(哔哩哔哩)1、游戏颠覆性的策略玩...