如何从自定义视图中访问layout_height?

Bra*_*ein 7 layout android custom-view

我有一个自定义视图,我只想访问xml布局值layout_height.

我目前正在获取该信息并在onMeasure期间存储它,但这仅在视图首次绘制时发生.我的视图是XY图,它需要尽早知道它的高度,以便它可以开始执行计算.

The view is on the fourth page of a viewFlipper layout, so the user may not flip to it for a while, but when they do flip to it, I would like the view to already contain data, which requires that I have the height to make the calculations.

Thanks!!!

dou*_*bou 12

工作:)...你需要改变"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..
}
Run Code Online (Sandbox Code Playgroud)


Moh*_*san 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();
}
Run Code Online (Sandbox Code Playgroud)


Kon*_*rov 5

public View(Context context, AttributeSet attrs)构造函数文档:

从 XML 扩充视图时调用的构造函数。当从 XML 文件构造视图时调用它,提供在 XML 文件中指定的属性。

因此,要实现您需要的功能,请为您的自定义视图提供一个构造函数,该构造函数将 Attributes 作为参数,即:

public CustomView(final Context context, AttributeSet attrs) {
    super(context, attrs);
    String height = attrs.getAttributeValue("android", "layout_height");
    //further logic of your choice..
}
Run Code Online (Sandbox Code Playgroud)

  • 命名空间应为“http://schemas.android.com/apk/res/android”(以 http:// 开头),否则高度将为空。 (2认同)

ami*_*phy 5

\xe2\x80\xa2Kotlin Version

\n\n

针对此问题编写的答案并未完全涵盖该问题。事实上,他们正在互相补足。总结一下答案,首先我们应该检查getAttributeValue返回值,然后如果layout_height定义为维度值,则使用以下方法检索它getDimensionPixelSize

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