Android的 - 如何从一个微调所选项目的值,并把它转换成字符串?(Android - How

2019-07-22 07:46发布

我读了这个线程很多类似的问题,但没有人帮助我。这是我的代码:

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

}

我宣布imc_met作为public String imc_met; 。 问题是,imc_met不包含微调的所选项目的价值,但它是空...

哪里的问题呢?

THX提前。

Answer 1:

使用:

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

代替:

imc_met = parent.getItemAtPosition(POS)的ToString();

更新:

似乎你在正确的方式分配监听到你的微调不是,这样做如下:

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

            }
        });


Answer 2:

试试这个:

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

对不起。 我忘了

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


Answer 3:

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

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


Answer 4:

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

这将通过价值得到指数。



Answer 5:

如果微调没有在的onCreate()方法定义然后必须使用此:

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


Answer 6:

试试这个代码在你onCreate()方法:

spinner.setOnItemSelectedListener(this);


文章来源: Android - How to get the selected item value from a spinner and put it into a string?