Java Android自定义视图获取多个属性

Java Android自定义视图获取多个属性,java,android,android-custom-view,Java,Android,Android Custom View,我正在Android中创建一个自定义视图。在它的构造函数中,我获得了在XML布局文件中设置的一些属性。代码如下所示: public LabeledEditText(Context context, AttributeSet attrs) { super(context, attrs); TypedArray styledAttrs = context.getTheme().obtainStyledAttributes(attrs, new int[] { android

我正在Android中创建一个自定义视图。在它的构造函数中,我获得了在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();
    }
}
问题在于,即使属性集中存在所有属性,AcquinStyleDatAttributes也无法获取所有属性。更奇怪的是,如果我改变int数组中id的顺序,我会得到不同的结果。例如,如果我使用以下顺序

new int[] { android.R.attr.id, android.R.attr.digits, android.R.attr.padding, android.R.attr.inputType }
new int[] {android.R.attr.digits, android.R.attr.padding, android.R.attr.inputType, android.R.attr.id }
我得到3个属性,但是如果我使用以下顺序

new int[] { android.R.attr.id, android.R.attr.digits, android.R.attr.padding, android.R.attr.inputType }
new int[] {android.R.attr.digits, android.R.attr.padding, android.R.attr.inputType, android.R.attr.id }
我回来了。我包括两个屏幕截图的手表窗口这两个案件。断点设置在try语句之后


在任何情况下,如果我一次获得一个属性,它对所有属性都有效。获取StyledAttributes是如何工作的?另外,我也不确定是否应该使用styledAttrs.getIndex(I)函数,但在解决当前函数后,这是一个问题。

尽管没有文档记录,但是,
获得StyleDattributes
需要一个排序数组,并且它的代码根据该假设进行了优化

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

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

  • 基于它们在资源中的相对位置
  • 通过检查它们的相对值并更改数组以匹配
  • 或者通过编程方式对数组元素进行排序
如果选择在运行时以编程方式对数组进行排序,请确保在调用
getString()
等时使用适当的(排序的)索引

另一种常见的解决方法是一次仅使用
actainStyledAttributes
获取单个值。(已对包含一个元素的数组进行排序。)

另外,我不确定是否应该使用styledAttrs.getIndex(I)函数

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

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