2010-03-17 27 views
4

我已经使用edittext和微调控件创建了组合框控件。 我想让android:prompt属性传递到 微调器,这意味着我需要在构造函数中捕获它,其中 将AttributeSet设置为传递给我的AttributeSet并将其设置在微调器上。 我无法弄清楚如何获得提示的值。 我想,如何检索自定义控件的XML属性

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

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

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

感谢

回答

6

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

0
  1. 定义的XML风格。对于前: <declare-styleable name="ComboBox"> <attr name="prompt" format="reference"/> </declare-styleable>

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

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

+0

这个,但你不应该忘记在布局xml:xmlns:app =“http://schemas.android.com/apk/res/package.name”中为你的自定义设置定义一个新的xml命名空间。并使用a.getString(R.stylable.option_name)来获得选项。 – MrSnowflake 2010-03-17 09:46:21

+1

非常感谢! a.getString(R.styleable.option_name)不起作用。我得到一个索引越界异常。我认为索引应该是数组中的索引,而不是资源ID。 使用android:prompt也可以,android.R.attr.prompt。 我的问题是在getsStyleAttributes方法上使用了错误的签名。我以为我必须使用主题。这些签名的工作原理如下: 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); – David 2010-03-17 14:55:38