代码之家  ›  专栏  ›  技术社区  ›  Brad Hein

如何从自定义视图中访问布局高度?

  •  7
  • Brad Hein  · 技术社区  · 15 年前

    layout_height .

    我目前正在获取这些信息,并在onMeasure期间存储这些信息,但这只发生在第一次绘制视图时。我的视图是XY图,它需要尽早知道它的高度,这样它就可以开始执行计算了。

    谢谢!!!

    3 回复  |  直到 4 年前
        1
  •  5
  •   Konstantin Burov    15 年前

    公共视图(上下文、属性集属性)

    当 从XML扩展视图。这是 在创建视图时调用 从XML文件构造, 提供的属性 在XML文件中指定。

    public CustomView(final Context context, AttributeSet attrs) {
        super(context, attrs);
        String height = attrs.getAttributeValue("android", "layout_height");
        //further logic of your choice..
    }
    
        2
  •  13
  •   chowey    7 年前

    http://schemas.android.com/apk/res/android "

    public CustomView(final Context context, AttributeSet attrs) {
        super(context, attrs);
        String height = attrs.getAttributeValue("http://schemas.android.com/apk/res/android", "layout_height");
        //further logic of your choice..
    }
    
        3
  •  4
  •   chowey    7 年前

    您可以使用:

    public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    
        int[] systemAttrs = {android.R.attr.layout_height};
        TypedArray a = context.obtainStyledAttributes(attrs, systemAttrs);
        int height = a.getDimensionPixelSize(0, ViewGroup.LayoutParams.WRAP_CONTENT);
        a.recycle();
    }
    
        4
  •  2
  •   aminography    5 年前

    Kotlin Version

    这个问题的答案并不完全涵盖这个问题。实际上,他们是在互相完善。为了总结答案,首先我们应该检查 getAttributeValue 返回值,则如果 layout_height getDimensionPixelSize

    val layoutHeight = attrs?.getAttributeValue("http://schemas.android.com/apk/res/android", "layout_height")
    var height = 0
    when {
        layoutHeight.equals(ViewGroup.LayoutParams.MATCH_PARENT.toString()) -> 
            height = ViewGroup.LayoutParams.MATCH_PARENT
        layoutHeight.equals(ViewGroup.LayoutParams.WRAP_CONTENT.toString()) -> 
            height = ViewGroup.LayoutParams.WRAP_CONTENT
        else -> context.obtainStyledAttributes(attrs, intArrayOf(android.R.attr.layout_height)).apply {
            height = getDimensionPixelSize(0, ViewGroup.LayoutParams.WRAP_CONTENT)
            recycle()
        }
    }
    
    // Further to do something with `height`:
    when (height) {
        ViewGroup.LayoutParams.MATCH_PARENT -> {
            // defined as `MATCH_PARENT`
        }
        ViewGroup.LayoutParams.WRAP_CONTENT -> {
            // defined as `WRAP_CONTENT`
        }
        in 0 until Int.MAX_VALUE -> {
            // defined as dimension values (here in pixels)
        }
    }