我有一个自定义视图,我只想访问 .xml 的 xml 布局值layout_height
。
我目前正在获取该信息并将其存储在 onMeasure 期间,但这仅在第一次绘制视图时发生。我的视图是一个 XY 图,它需要尽早知道它的高度,以便它可以开始执行计算。
该视图位于 viewFlipper 布局的第四页,因此用户可能暂时不会翻转到它,但是当他们翻转到它时,我希望视图已经包含数据,这需要我有高度进行计算。
谢谢!!!
我有一个自定义视图,我只想访问 .xml 的 xml 布局值layout_height
。
我目前正在获取该信息并将其存储在 onMeasure 期间,但这仅在第一次绘制视图时发生。我的视图是一个 XY 图,它需要尽早知道它的高度,以便它可以开始执行计算。
该视图位于 viewFlipper 布局的第四页,因此用户可能暂时不会翻转到它,但是当他们翻转到它时,我希望视图已经包含数据,这需要我有高度进行计算。
谢谢!!!
那工作:)...您需要为“ http://schemas.android.com/apk/res/android ”更改“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();
}
从 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..
}
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)
}
}