我在这个帖子上读了许多类似的问题,但没有一个能帮助我...... 这是我的代码:
@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不包含微调器的选定项的值,但它是null ...
问题出在哪里?
提前谢谢。答案 0 :(得分:33)
使用:
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
}
});
答案 1 :(得分:7)
试试这个:
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();
}
}
答案 2 :(得分:2)
是
imc_met=spinner.getSelectedItem().toString();
不
imc_met=Spinner.getSelectedItem().toString();
答案 3 :(得分:1)
int position = Arrays.asList(getResources().getStringArray(R.array.country_value_array)).indexOf(address.getCountry());
这将按值得到索引。
答案 4 :(得分:0)
如果未在onCreate()方法中定义微调器,则必须使用:
String spinner_value = ((Spinner)findViewById(R.id.spinner1)).getSelectedItem().toString();