如何获取自定义控件的XML属性

4

我创建了一个带有EditText和Spinner的组合框控件。 我想让android:prompt属性传递到Spinner上,这意味着我需要在构造函数中捕获它并将其设置在Spinner上。 我无法弄清如何获取提示的值。 我正在尝试,

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

我得到了0,这意味着它没有找到属性。我还做了一个ta.count(),返回了0。所以我什么也没得到。

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

谢谢

2个回答

6

我刚刚写了一个回答,解释了如何使用自定义UI元素与XML的整个过程。在你的情况下,不需要声明一个styleable,因为你不需要自定义属性。使用 android.R.attr.prompt 作为 int id 就可以了。只有当你在 styleable 中定义了属性并通过将 R.styleable.className 传递到 obtainStyledAttributes 中检索它们时,R.styleable.className_attributeName 才会起作用。


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方法获取特定属性。


这个,但是你不应该忘记在布局xml中为自定义设置定义一个新的xml命名空间:xmlns:app="http://schemas.android.com/apk/res/package.name"。并使用a.getString(R.stylable.option_name)来获取选项。 - MrSnowflake
2
a.getString(R.styleable.option_name)无法正常工作,我得到了一个数组越界异常。我认为索引应该是数组内的索引,而不是资源ID。使用android:prompt也可以,android.R.attr.prompt。 我的问题在于在obtainStyleAttributes方法上使用了错误的签名。我以为我必须使用一个主题。这些签名可行: 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接