Set text of spinner before item is selected
Asked Answered
T

2

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?

Trudy answered 3/6, 2012 at 0:40 Comment(1)
Possible duplicate of How to make an Android Spinner with initial text "Select One"Kilometer
A
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
        }
    }
});
Averroes answered 3/6, 2012 at 2:23 Comment(4)
Is there a way to insert it from a string resource?Trudy
Yeah, just add it as the first of the entries in your array resource. I edited my answer to provide an example.Averroes
+1, Good trick, but it would be greate if we could remove the radio button from select one item.Troudeloup
@SahilMahajanMj How about not having it in the dropdown ar all? Check this answer for a way to do thar.Averroes
T
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" 
/> 
Term answered 3/6, 2012 at 0:58 Comment(2)
Not what the OP wanted. He wants it in the spinner, not as the header for it.Averroes
check this post , it gives miltitude way to do what you want. #868018Term

© 2022 - 2024 — McMap. All rights reserved.