How to retrieve XML attribute for custom control

China☆狼群 提交于 2019-12-29 07:53:35

问题


I've created a combo box control with a edittext and spinner. I'm trying to let the android:prompt attribute be passed onto the spinner, which means I need to catch it in the constructor which passes my the AttributeSet and set it on the spinner. I can't figure out how to get the value of the prompt. I'm trying,

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

I get back 0, which means it didn't find the attribute. I also did a ta.count() which returned 0. So I'm not getting anything back.

My XML simply defines an android:prompt value.

Thanks


回答1:


I just wrote an answer explaining the whole process for using XML with custom UI elements. In your case, there is no need to declare a styleable, as you don't need custom attributes. Using android.R.attr.prompt as the int id will work fine. R.styleable.className_attributeName will only work if you defined your attributes in the styleable and you retrieved them by passing R.styleable.className into obtainStyledAttributes.




回答2:


  1. Define a style in the xml. For ex : <declare-styleable name="ComboBox"> <attr name="prompt" format="reference"/> </declare-styleable>

  2. To get the value in the constructor use : TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ComboBox);

Use the TypedArray get methods to get the particular attribute.



来源:https://stackoverflow.com/questions/2460074/how-to-retrieve-xml-attribute-for-custom-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!