gpt4 book ai didi

java - Android自定义 View 获取多个属性

转载 作者:行者123 更新时间:2023-11-30 01:55:44 26 4
gpt4 key购买 nike

我正在 Android 中创建自定义 View 。在它的构造函数中,我获得了一些在 XML 布局文件中设置的属性。代码是这样的:

public LabeledEditText(Context context, AttributeSet attrs) {
super(context, attrs);

TypedArray styledAttrs = context.getTheme().obtainStyledAttributes(attrs, new int[] { android.R.attr.id, android.R.attr.digits, android.R.attr.padding, android.R.attr.inputType }, 0, 0);
try {
int id = styledAttrs.getResourceId(styledAttrs.getIndex(0), -1);
String digits = styledAttrs.getString(styledAttrs.getIndex(1));
float padding = styledAttrs.getDimension(styledAttrs.getIndex(2), 0.1f);
int inputType = styledAttrs.getInt(styledAttrs.getIndex(3), -1);
} finally {
styledAttrs.recycle();
}
}

问题是 obtainStyledAttributes 并没有获得所有的属性,即使它们存在于属性集中。更奇怪的是,如果我更改 int 数组中 id 的顺序,我会得到不同的结果。例如,如果我使用以下顺序

new int[] { android.R.attr.id, android.R.attr.digits, android.R.attr.padding, android.R.attr.inputType }

我得到了 3 个属性,但是如果我使用以下顺序

new int[] {android.R.attr.digits, android.R.attr.padding, android.R.attr.inputType, android.R.attr.id }

我回来了 2。我附上了这 2 个案例的 watches 窗口的 2 个屏幕截图。断点设置在 try 语句之后。

1st ordering

2nd ordering

无论如何,如果我一次获得一个属性,它对所有属性都有效。 obtainStyledAttributes 是如何工作的?另外我不确定是否应该使用 styledAttrs.getIndex(i) 函数,但这是当前问题解决后的问题。

最佳答案

虽然没有记录,obtainStyledAttributes 需要一个排序数组,并且它的代码根据该假设进行了优化。

因此您需要提供您的 styledAttrs 数组,其中的元素根据其 id 值按升序排序。

有几种方法可以确定正确的顺序:

  • 基于他们在资源中的相对位置
  • 通过检查它们的相对值并更改数组以匹配
  • 或以编程方式对数组元素进行排序

如果您选择在运行时以编程方式对数组进行排序,请确保在调用 getString() 等时使用适当的(排序的)索引。

另一种常见的解决方法是一次仅使用 obtainStyledAttributes 获取一个值。 (只有一个元素的数组已经排序。)

Also I'm not sure if I should use the styledAttrs.getIndex(i) function or not

我认为只有当您循环遍历 TypedArray 时才需要这样做,并且其中一些元素可能没有值;它基本上为您“隐藏”了空元素,就好像它是一个稀疏数组一样。一般来说,我认为没有必要,除非您以特定方式访问样式化资源,例如在实现自定义 View 时。

大多数时候我使用与 View 完全无关的自定义主题属性,在这些情况下我总是发现 TypedArray.getIndex() 是多余的。

关于java - Android自定义 View 获取多个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32273576/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com