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分钟了解!hhpoker是... 第1分钟了解!hhpoker是正规平台吗!其实有辅助技巧(有挂规律)-哔哩哔哩1、hhpoker是正...
第六分钟了解!牌乐门安全黑科技... 第六分钟了解!牌乐门安全黑科技是真的吗!原来是有辅助app(有挂攻略)-哔哩哔哩;1、每一步都需要思...
第9分钟了解!土豪联盟辅助!本... 第9分钟了解!土豪联盟辅助!本来有辅助软件(真实有挂)-哔哩哔哩小薇(辅助器软件下载)致您一封信;亲...
七分钟了解!智星德州插件!总是... 七分钟了解!智星德州插件!总是一直都是有辅助方法(真实有挂)-哔哩哔哩1、智星德州插件免费脚本咨询教...
6分钟了解!广丰510k辅助插... 6分钟了解!广丰510k辅助插件!真是有辅助脚本(有挂技巧)-哔哩哔哩1、玩家可以在广丰510k辅助...
九分钟了解!威信茶馆app插件... 九分钟了解!威信茶馆app插件!总是有辅助攻略(有挂技术)-哔哩哔哩运威信茶馆app插件辅助工具,进...
2分钟了解!战神辅助众包!好像... 2分钟了解!战神辅助众包!好像存在有辅助脚本(有挂教学)-哔哩哔哩1、上手简单,内置详细流程视频教学...
第三分钟了解!来趣广西辅助!真... 第三分钟了解!来趣广西辅助!真是真的是有辅助方法(详细教程)-哔哩哔哩1、下载好来趣广西辅助透视辅助...
七分钟了解!拱趴大菠萝辅助工具... 七分钟了解!拱趴大菠萝辅助工具下载!一直存在有辅助教程(有挂细节)-哔哩哔哩该软件可以轻松地帮助玩家...
第3分钟了解!九九山城万州版脚... 第3分钟了解!九九山城万州版脚本!切实真的是有辅助插件(详细教程)-哔哩哔哩1、操作简单,无需九九山...