【问题标题】:TypedArray and styleable attributes: getIndexCount() vs. length()TypedArray 和 styleable 属性:getIndexCount() 与 length()
【发布时间】:2011-12-06 19:14:09
【问题描述】:

我正在解析自定义属性,但遇到了一些奇怪的事情。假设我的解析器看起来像这样:

final TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.Item);
final int size = attributes.getIndexCount();

for(int i = 0; i < size; i++) {
   final int attr = attributes.getIndex(i);
   if(attr == R.styleable.Item_custom_attrib) {
      final int resourceId = attributes.getResourceId(attr, -1);
      if(resourceId == -1)
         throw new Resources.NotFoundException("The resource specified was not found.");
...
}
attributes.recycle();

这行得通。现在,如果我将第 2 行替换为 final int size = attributes.length();,这意味着我得到了:

final TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.Item);
final int size = attributes.length();

for(int i = 0; i < size; i++) {
   final int attr = attributes.getIndex(i);
   if(attr == R.styleable.Item_animation_src) {
      final int resourceId = attributes.getResourceId(attr, -1);
      if(resourceId == -1)
         throw new Resources.NotFoundException("The resource specified was not found.");
...
}
attributes.recycle();

这与我抛出的 Resources.NotFoundException 一起崩溃。换句话说,attributes.getResourceId(attr, -1); 返回默认的-1 值。

现在,在这种特殊情况下,只有一个自定义属性。 attributes.getIndexCount()attributes.length() 都返回 1,因为我的属性中确实有一个值。这意味着getIndex(i) 应该返回相同的数字,但事实并非如此。这意味着getIndexCount() 不仅仅是return the number of indices in the array that have data。这两种方法到底有什么区别,一种允许我获取属性而另一种不允许?

【问题讨论】:

    标签: android custom-attributes


    【解决方案1】:

    我只是在摆弄这个,发现整个事情令人困惑,但我想我已经弄清楚了:

    所以你已经在 attrs.xml 中为你的类声明了 N 个属性。 现在得到的TypedArray的大小是N。它总是传递相同大小的数组。

    但也许您在 layout xml 中只定义了 X 属性,所以 getIndexCount() 返回 X。

    在您的小部件的初始化中,如果您要问自己有多少和哪些属性 在 xml 中定义,您将首先找出有多少,使用 getIndexCount()。 然后你从0 to getIndexCount()-1循环并询问TypedArray:“什么是索引 第 i 个 提供 属性?”。

    所以假设你想强制在 xml 中设置一个属性,你现在可以检查这个 因为对 getIndex() 的调用之一必须返回您要查找的 id。

    但您始终可以忽略这一点,并提供默认值。然后你就可以拨打a.getInteger( R.styleable.MyClass_MyAttribute, defaultValue );

    您可以检查 R.java 以查看每个类的所有属性 ID 都从 0 开始。生成的 cmets 也有助于理解。

    【讨论】:

    • 啊,这很有道理。我猜在我的项目中,我有一个没有定义属性值的自定义布局,所以它没有数据,这意味着getIndexCount() 将返回与length() 不同的值。谢谢。
    【解决方案2】:

    您的问题确实很简单,确实很常用,像这样,首先定义一个类myview extends View{...},然后将myview应用于layout.xml并定义一些属性,如'textColor =“#ffffffff”'等等,在 layout.xml 中,所以你的 a.getIndexCount() 返回不为空或不为零,这是你所期望的。

    现在我换个问题,你定义一个类 myview 扩展 Object,注意不是扩展 View 类,你永远不会使用 layout.xml 到你自定义的 myview。整个事情就像 android定义的类View实现了Drawable.Callback、Drawable.Callback2、KeyEvent.Callback、AccessibilityEventSource{...},没有layout.xml,没有extends View方便, 唯一可以使用的资源是 attrs.xml,styles.xml。

    所以你可以做些什么来让 a.getIndexCount() 返回不为空或不为零 喜欢我的顶:why TypedArray.getIndexCount() always returns 0

    【讨论】:

      猜你喜欢
      • 2016-08-03
      • 2014-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-28
      • 2015-06-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多