Set text of spinner before item is selected

前端 未结 2 1471
醉话见心
醉话见心 2021-02-15 18:47

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 lis

相关标签:
2条回答
  • 2021-02-15 19:01

    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" 
    /> 
    
    0 讨论(0)
  • 2021-02-15 19:04

    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
            }
        }
    });
    
    0 讨论(0)
提交回复
热议问题