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

相关内容

热门资讯

WPK俱乐部!aapoker工... WPK俱乐部!aapoker工具透视挂ai,werplan外卦神器,都是真的有ai透视挂举措1、这是...
WPK透视版!AApoker插... WPK透视版!AApoker插件透视ai,AApoker脚本,总是真的有ai透视资料亲,关键说明,A...
WPK脚本!德州扑克教程开挂a... WPK脚本!德州扑克教程开挂ai,德扑之心免费透视,都是存在有ai开挂学习运德扑之心免费透视辅助工具...
WPK辅助!红龙扑克神器辅助a... WPK辅助!红龙扑克神器辅助ai,来玩app破解版,都是是真的有ai辅助法子1、进入游戏-大厅左侧-...
WPK辅助!德扑之星脚本辅助器... WPK辅助!德扑之星脚本辅助器ai,AApoker靠谱,总是有ai辅助器手段1、用户打开应用后不用登...
WPK链接!智星菠萝德州app... WPK链接!智星菠萝德州app开挂ai,aapoker辅助器是真的吗,本来是有ai开挂诀窍1)aap...
WPK德州局!WPK神器辅助器... WPK德州局!WPK神器辅助器ai,aapoker辅助插件工具,其实是真的有ai辅助器手筋1、全新机...
WPK软件!红龙PoKer技巧... WPK软件!红龙PoKer技巧开挂ai,we poker免费辅助器,总是是有ai开挂模板1、用户打开...
WPK四人!AApoker插件... WPK四人!AApoker插件透视挂ai,德普之星怎么开辅助,原来存在有ai透视挂法门1)德普之星怎...
WPK控制牌!AApoker技... WPK控制牌!AApoker技巧透视挂ai,德扑之心免费透视,确实真的是有ai透视挂指南书1、每一步...