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、超多福利:超高返利,海量正版游戏,慧玩免费透视...
交流学习经验!丰城瓜瓜棋牌开挂... 交流学习经验!丰城瓜瓜棋牌开挂脚本(透视挂),丰城瓜瓜棋牌竟然是有透视挂讲义1)丰城瓜瓜棋牌有没有挂...
技巧知识分享!百顺娱乐可以开挂... 技巧知识分享!百顺娱乐可以开挂吗(辅助器),百顺娱乐总是真的有辅助器项目1、不需要AI权限,帮助你快...
终于清楚!众兴乐开挂技巧(外挂... 终于清楚!众兴乐开挂技巧(外挂),众兴乐果然是有外挂讲义暗藏猫腻,小编详细说明众兴乐破解器有用吗(w...
总算了解!雀神韵关麻将怎么开挂... 总算了解!雀神韵关麻将怎么开挂(外挂),雀神韵关麻将都是真的是有外挂要领一、雀神韵关麻将可以开透视的...
一分钟了解!微乐长春麻将究竟有... 一分钟了解!微乐长春麻将究竟有没有挂(开挂),微乐长春麻将切实存在有开挂教程书1、下载好微乐长春麻将...
我来教大家!川渝互娱到底有没有... 我来教大家!川渝互娱到底有没有挂(透视挂),川渝互娱真是有透视挂技巧1、打开软件启动之后找到中间准星...