4

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

Janusz
  • 176,216
  • 111
  • 293
  • 365
David
  • 2,585
  • 5
  • 32
  • 43

2 Answers2

6

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.

Community
  • 1
  • 1
Casebash
  • 100,511
  • 79
  • 236
  • 337
0
  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.

Karan
  • 12,434
  • 6
  • 37
  • 33
  • This, but you should not forget to define a new xml namespace for your custom settings in the layout xml: xmlns:app="http://schemas.android.com/apk/res/package.name". And use a.getString(R.stylable.option_name) to get the option. – MrSnowflake Mar 17 '10 at 09:46
  • 1
    Great thanks! a.getString(R.styleable.option_name) does not work. I get an index out of bounds exception. I presume the index is supposed to be the index within the array, not a resource id. Using android:prompt also works, android.R.attr.prompt. My problem was using the wrong signature on the obtainStyleAttributes method. I thought I had to use a Theme. These signatures work: TypedArray a = context.obtainStyledAttributes(attrs, new int[] { android.R.attr.prompt }); or context.obtainStyledAttributes(attrs, new int[] { android.R.attr.prompt}, 0, 0 ); Then a.getResourceId(0, 0); – David Mar 17 '10 at 14:55