Android - How to get the selected item value from

2019-02-06 15:07发布

问题:

i read many similar questions on this thread, but none of them help me... This is my code:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Spinner spinner = (Spinner) findViewById(R.id.imc_spinner);
    // Create an ArrayAdapter using the string array and a default spinner layout
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
    R.array.imc_array, android.R.layout.simple_spinner_item);
    // Specify the layout to use when the list of choices appears
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    // Apply the adapter to the spinner
    spinner.setAdapter(adapter);

}

public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
    // An item was selected. You can retrieve the selected item using

    imc_met = parent.getItemAtPosition(pos).toString();

}

I declare imc_met as public String imc_met;. The problem is that imc_met does not contain the value of the selected item of the spinner, but it's null...

Where's the problem?

Thx in advance.

回答1:

Use:

imc_met=Spinner.getSelectedItem().toString();

Instead:

imc_met = parent.getItemAtPosition(pos).toString();

Updated:

Seem you assigning Listener to your spinner not in correct way, do something like below:

spin.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                String imc_met=spin.getSelectedItem().toString();

            }

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

            }
        });


回答2:

Try this:

imc_met=Spinner.getSelectedItem().toString();

I'm sorry. I forgot

spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
        imc_met=Spinner.getSelectedItem().toString();
        }
    }


回答3:

is

imc_met=spinner.getSelectedItem().toString();

not

imc_met=Spinner.getSelectedItem().toString();


回答4:

int position = Arrays.asList(getResources().getStringArray(R.array.country_value_array)).indexOf(address.getCountry());

This will get index by the value.



回答5:

If spinner isn't define in onCreate() method then have to use this:

String spinner_value = ((Spinner)findViewById(R.id.spinner1)).getSelectedItem().toString(); 


回答6:

Try this code in your onCreate() method:

spinner.setOnItemSelectedListener(this);