8

I have a spinner with three items and I use an XML string-array resource to feed it. When you open an activity the spinner normally shows the first item that's in the array list. I'd like to change that and show the text "Select one" in the spinner, before an item is selected.

How can I do that?

Perception
  • 79,279
  • 19
  • 185
  • 195
JohnD
  • 201
  • 2
  • 4
  • 12
  • Possible duplicate of [How to make an Android Spinner with initial text "Select One"](http://stackoverflow.com/questions/867518/how-to-make-an-android-spinner-with-initial-text-select-one) – blahdiblah Mar 09 '13 at 11:24

2 Answers2

10

You can do that one of two ways.

1) Add "Select One" as the first item in your xml and code your listener to ignore that as a selection.

2) Create a custom adapter to insert it as the first line,

EDIT

In your resources

<string-array name="listarray">
    <item>Select One</item>
    <item>Item One</item>
    <item>Item Two</item>
    <item>Item Three</item>
</string-array>

In your onItemSelected Listener:

spinnername.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
    public void onNothingSelected(AdapterView<?> parent) {
    }
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        if (pos == 0) {
        }else {
            // Your code to process the selection
        }
    }
});
Barak
  • 16,318
  • 9
  • 52
  • 84
  • Is there a way to insert it from a string resource? – JohnD Jun 03 '12 at 12:29
  • Yeah, just add it as the first of the entries in your array resource. I edited my answer to provide an example. – Barak Jun 03 '12 at 12:57
  • 1
    +1, Good trick, but it would be greate if we could remove the radio button from select one item. – Sahil Mahajan Mj Sep 15 '12 at 08:36
  • @SahilMahajanMj How about not having it in the dropdown ar all? Check [this answer](http://stackoverflow.com/a/11484295/1105376) for a way to do thar. – Barak Sep 15 '12 at 13:33
1

To set a default text for the spinner you have to use android:prompt=@string/SelectOne for your spinner Where SelectOne is defined in your string.xml .

Example :

<Spinner android:id="@+id/spinnerTest"  
 android:layout_marginLeft="50px"
 android:layout_width="fill_parent"                  
 android:drawSelectorOnTop="true"
 android:layout_marginTop="5dip"
 android:prompt="@string/SelectOne"
 android:layout_marginRight="30px"
 android:layout_height="35px" 
/> 
113408
  • 3,364
  • 6
  • 27
  • 54
  • Not what the OP wanted. He wants it in the spinner, not as the header for it. – Barak Jun 03 '12 at 02:24
  • 1
    check this post , it gives miltitude way to do what you want. http://stackoverflow.com/questions/867518/how-to-make-an-android-spinner-with-initial-text-select-one – 113408 Jun 03 '12 at 12:17