【问题标题】:How to retrieve XML attribute for custom control如何检索自定义控件的 XML 属性
【发布时间】:2011-01-28 10:33:05
【问题描述】:

我创建了一个带有编辑文本和微调器的组合框控件。 我试图让 android:prompt 属性传递到 微调器,这意味着我需要在构造函数中捕获它 传递我的 AttributeSet 并将其设置在微调器上。 我不知道如何获得提示的价值。 我在努力,

int[] ra = { android.R.attr.prompt };
TypedArray ta = context.getTheme().obtainStyledAttributes(ra); 
int id = ta.getResourceId(0, 0); 

我返回 0,这意味着它没有找到该属性。 我还做了一个返回 0 的 ta.count()。所以我没有得到任何回报。

我的 XML 只是定义了一个 android:prompt 值。

谢谢

【问题讨论】:

    标签: android custom-controls


    【解决方案1】:

    我刚刚写了一个答案,解释了using XML with custom UI elements 的整个过程。在您的情况下,无需声明样式,因为您不需要自定义属性。使用 android.R.attr.prompt 作为 int id 可以正常工作。 R.styleable.className_attributeName 仅在您在样式中定义属性并通过将R.styleable.className 传递给obtainStyledAttributes 来检索它们时才有效。

    【讨论】:

      【解决方案2】:
      1. 在 xml 中定义样式。例如: <declare-styleable name="ComboBox"> <attr name="prompt" format="reference"/> </declare-styleable>

      2. 要在构造函数中获取值,请使用: TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ComboBox);

      使用 TypedArray 获取方法来获取特定属性。

      【讨论】:

      • 这个,但您不应该忘记在布局 xml 中为您的自定义设置定义一个新的 xml 命名空间:xmlns:app="schemas.android.com/apk/res/package.name"。并使用 a.getString(R.stylable.option_name) 获取选项。
      • 非常感谢! a.getString(R.styleable.option_name) 不起作用。我得到一个索引越界异常。我认为索引应该是数组中的索引,而不是资源 ID。使用 android:prompt 也可以,android.R.attr.prompt。我的问题是在获取样式属性方法上使用了错误的签名。我以为我必须使用主题。这些签名有效: TypedArray a = context.obtainStyledAttributes(attrs, new int[] { android.R.attr.prompt });或 context.obtainStyledAttributes(attrs, new int[] { android.R.attr.prompt}, 0, 0 );然后a.getResourceId(0, 0);
      猜你喜欢
      • 1970-01-01
      • 2014-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-07
      相关资源
      最近更新 更多