简体   繁体   中英

Android - How to get the selected item value from a spinner and put it into a string?

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.

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

            }
        });

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();
        }
    }

is

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

not

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

这将通过值获得索引。

如果在onCreate()方法中没有定义微调器,则必须使用:

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

onCreate()方法中尝试以下代码:

spinner.setOnItemSelectedListener(this);

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