我有一个自定义视图,我只是希望访问XML布局值 layout_height.

我目前正在获取这些信息并在Oneasure中存储,但这只有首次绘制视图时才会发生。我的观点是XY图,它需要尽早了解其高度,以便可以开始执行计算。

该视图位于ViewFlipper布局的第四页上,因此用户可能不会在一段时间内翻转,但是当他们确实翻转时,我希望视图已经包含数据,这要求我有高度进行计算。

谢谢!!!

有帮助吗?

解决方案

公众视图(上下文上下文,属性attrs) 构造函数文档:

从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..
}

其他提示

这项工作:)...您需要更改“ Android”。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..
}

您可以使用以下方式:

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();
}

为此问题写的答案并不能完全涵盖该问题。实际上,他们正在互相完成。要总结答案,首先我们应该检查 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)
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top