OGeek|极客世界-中国程序员成长平台

标题: android - onMeasure 自定义 View 说明 [打印本页]

作者: 菜鸟教程小白    时间: 2022-8-1 01:19
标题: android - onMeasure 自定义 View 说明

我试图做自定义组件。我扩展了View上课并在 onDraw 中画图被覆盖的方法。为什么我需要覆盖 onMeasure ?如果我没有,一切看起来都是正确的。有人可以解释一下吗?我应该如何写我的onMeasure方法?我看过几个教程,但每个教程都有点不同。有时他们会调用 super.onMeasure最后,有时他们使用 setMeasuredDimension并没有调用它。区别在哪里?

毕竟我想使用几个完全相同的组件。我将这些组件添加到我的 XML文件,但我不知道它们应该有多大。我想稍后在自定义组件类中设置它的位置和大小(为什么我需要在 onMeasure 中设置大小,如果在 onDraw 中,当我绘制它时也可以正常工作)。我到底什么时候需要这样做?



Best Answer-推荐答案


onMeasure()您是否有机会告诉 Android 您希望自定义 View 依赖于父级提供的布局约束有多大?这也是您的自定义 View 了解这些布局约束的机会(如果您希望在 match_parent 情况下与 wrap_content 情况下表现不同)。这些约束被打包到 MeasureSpec传递给方法的值。以下是众数值的粗略相关性:

  • 正是 表示 layout_widthlayout_height value 被设置为一个特定的值。你可能应该把你的 View 设为这个大小。这也可以在 match_parent 时触发。用于将大小精确设置为父 View (这取决于框架中的布局)。
  • AT_MOST 通常表示 layout_widthlayout_height值设置为 match_parentwrap_content其中需要最大尺寸(这取决于框架中的布局),并且父尺寸的尺寸是值。你不应该比这个尺寸大。
  • 未指定 通常表示 layout_widthlayout_height值设置为 wrap_content没有限制。你可以是任何你想要的尺寸。一些布局还使用此回调来确定您想要的尺寸,然后再确定在第二次测量请求中实际再次传递给您的规范。

  • onMeasure() 存在的契约(Contract)是setMeasuredDimension() 必须 最后以您希望 View 的大小调用。此方法被所有框架实现调用,包括在 View 中找到的默认实现。 ,这就是为什么调用 super 是安全的相反,如果这适合您的用例。

    当然,因为框架确实应用了默认实现,所以您可能没有必要重写此方法,但是如果您不这样做,并且如果您布置了您的带有 wrap_content 的自定义 View 在这两个方向上,您的 View 可能根本不显示,因为框架不知道它有多大!

    通常,如果您要覆盖 View而不是另一个现有的小部件,提供一个实现可能是一个好主意,即使它像这样简单:
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    
        int desiredWidth = 100;
        int desiredHeight = 100;
    
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
    
        int width;
        int height;
    
        //Measure Width
        if (widthMode == MeasureSpec.EXACTLY) {
            //Must be this size
            width = widthSize;
        } else if (widthMode == MeasureSpec.AT_MOST) {
            //Can't be bigger than...
            width = Math.min(desiredWidth, widthSize);
        } else {
            //Be whatever you want
            width = desiredWidth;
        }
    
        //Measure Height
        if (heightMode == MeasureSpec.EXACTLY) {
            //Must be this size
            height = heightSize;
        } else if (heightMode == MeasureSpec.AT_MOST) {
            //Can't be bigger than...
            height = Math.min(desiredHeight, heightSize);
        } else {
            //Be whatever you want
            height = desiredHeight;
        }
    
        //MUST CALL THIS
        setMeasuredDimension(width, height);
    }
    

    希望有帮助。

    关于android - onMeasure 自定义 View 说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12266899/






    欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) Powered by Discuz! X3.4