【问题标题】:Android custom view obtain multiple attributesAndroid自定义view获取多个属性
【发布时间】:2015-08-28 14:37:12
【问题描述】:

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

问题是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 个案例的手表窗口的 2 个屏幕截图。断点是在 try 语句之后设置的。

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

【问题讨论】:

    标签: java android android-custom-view


    【解决方案1】:

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

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

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

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

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

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

    我也不确定是否应该使用 styledAttrs.getIndex(i) 函数

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

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

    【讨论】:

      猜你喜欢
      • 2014-03-18
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 2015-09-28
      • 2014-02-16
      • 1970-01-01
      • 2020-04-22
      • 2012-05-30
      相关资源
      最近更新 更多