简体   繁体   中英

Why does 'spinner.getSelectedItem' only retrieve the first item on the list?

I have a spinner in my application, and I (obviously) want the app to do things based on what item does the user select from the spinner's list. However, using this:

String itemFromSpinner = spinner.getSelectedItem().toString();

only retrieves the first item that is on the list. I also need it to be in String , because I then use the item in an if like this:

TextView textView = (TextView)findViewById(R.id.textView);
if (itemFromSpinner == "Mars") {
textView.setText("The fourth planet.");
} else {}

The code itself will then be more complicated. Anyway, here is my XML file of the spinner:

<string-array name="planets_array">
        <item>Mercury</item>
        <item>Venus</item>
        <item>Earth</item>
        <item>Mars</item>
        <item>Jupiter</item>
        <item>Saturn</item>
        <item>Uranus</item>
        <item>Neptune</item>
</string-array>

EDIT Here is the code for spinner :

Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
        R.array.planets_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);

try creating a listener inside onCreate for your spinner

spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?>arg0, View view, int arg2, long arg3) {

        String selected_val= spinner.getSelectedItem().toString();

        Toast.makeText(getApplicationContext(), selected_val ,
                Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

    }
});

good luck

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM