公共类MainActivity扩展了AppCompatActivity {
Spinner spinner;
ArrayAdapter<CharSequence> adapter;
int noc = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner =(Spinner)findViewById(R.id.spinner);
String text= spinner.getSelectedItem().toString();
adapter= ArrayAdapter.createFromResource(this,R.array.Coffee_names,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(),parent.getItemIdAtPosition(position) + " is selected",Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
当我将“String text = spinner.getSelectedItem()。toString();”添加到我的代码中时,我的应用程序停止,但是当我从程序中删除此行时,它可以正常工作。但是当我从下拉列表中选择一个项目时,它会选择4。 我希望它说出我选择的项目的名称而不是索引值。 请帮忙。
答案 0 :(得分:1)
我认为应该是:
Toast.makeText(getBaseContext(), parent.getSelectedItem() + " is selected", Toast.LENGTH_SHORT).show();
答案 1 :(得分:0)
替代方式
final String[] coffeeNames = getResources().getStringArray(R.array.Coffee_names);
spinner.setAdapter(new ArrayAdapter<>(activity, android.R.layout.simple_list_item_1, coffeeNames));
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selectedCoffeeName = coffeeNames[position];
Toast.makeText(getBaseContext(), selectedCoffeeName + " is selected", Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});