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

相关内容

热门资讯

一分钟了解辅助!金虎爷辅助多功... 一分钟了解辅助!金虎爷辅助多功能AI脚本,金虎爷本来真的有辅助脚本金虎爷破解侠是真的助透视。每个模型...
重大通报作弊器!山西奇迹麻将作... 重大通报作弊器!山西奇迹麻将作弊器多功能AIapp,山西奇迹麻将切实是有作弊器app1.山西奇迹麻将...
避坑细节透视器!十三张麻将透视... 避坑细节透视器!十三张麻将透视器多功能AI脚本,十三张麻将一贯真的是有透视器脚本1、完成十三张麻将有...
分享实测透视器!土豪老友麻将透... 分享实测透视器!土豪老友麻将透视器多功能AI技巧,土豪老友麻将原来真的是有透视器技巧1、超多福利:超...
交流学习经验外挂!长城互娱外挂... 交流学习经验外挂!长城互娱外挂多功能AI技巧,长城互娱果然真的有外挂技巧1、长城互娱破解器简单,长城...
让我来分享经验透视挂!钱柜手游... 让我来分享经验透视挂!钱柜手游透视挂多功能AI攻略,钱柜手游一直真的有透视挂攻略1、任何钱柜手游透视...
玩家必备教程辅助器!正宗青海麻... 玩家必备教程辅助器!正宗青海麻将辅助器多功能AI技巧,正宗青海麻将切实真的是有辅助器技巧亲,关键说明...
技术分享透视器!微友南昌麻将透... 技术分享透视器!微友南昌麻将透视器多功能AI脚本,微友南昌麻将果然是真的有透视器脚本1、微友南昌麻将...
技术分享外挂!途乐竞技外挂多功... 技术分享外挂!途乐竞技外挂多功能AI攻略,途乐竞技切实真的是有外挂攻略1、途乐竞技脚本辅助下载、途乐...
分辨真假作弊器!来来台安麻将作... 分辨真假作弊器!来来台安麻将作弊器多功能AIapp,来来台安麻将确实真的有作弊器app1、这是跨平台...