我想在textView
中显示所选项目时,从我实施的微调器的下拉列表中选择AdapterView.OnItemSelectedListener
但是当我选择项目时,null/empty
总是@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setAdapter(new CustomAdapter(MainActivity.this, Languages));
btn.setOnClickListener(this);
spinner.setOnItemSelectedListener(this);
}
@Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
item = (String)parent.getItemAtPosition(position);
Toast.makeText(MainActivity.this, item.toString(),
Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
这是我的代码:
enum CustomCellIdentifiers
{
static let cellForCountry = "cellForCountry"
static let cellForCity = "cellForCity"
static let cellForStoreType = "cellForStoreType"
}
答案 0 :(得分:1)
SO答案来源:https://stackoverflow.com/a/49301966/5461982
我知道这是一个老问题了,但是如果遇到其他任何人,请确保检查您为Spinner设置的适配器的自定义实现会覆盖getItem
方法:
@Override
public Object getItem(int position) {
return spinnerItems.get(position);
}
默认情况下,在实现自定义BaseAdapter
时需要重写此方法,但默认返回类型为null
。确保将返回类型修改为return spinnerItems.get(position)
。
希望这会有所帮助,我花了大约30分钟的时间尝试解决此问题!
答案 1 :(得分:0)
试试这个,
String selected_item = spinner.getSelectedItem().toString();
答案 2 :(得分:0)
只需从String Array中检索值:
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
final String item = Languages[position];
Toast.makeText(MainActivity.this, item, Toast.LENGTH_SHORT).show();
}
答案 3 :(得分:0)
试试这个
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
sSelectedItem = arr_spiner.get(spinner.getSelectedItemPosition())
.getName();
txtSpinnerValue.setText(sSelectedItem);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
https://stackoverflow.com/questions/45159011/spinner-item-is-not-visible-data-is-coming-from-server-android/45161202#45161202
答案 4 :(得分:0)
试一下
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setAdapter(new CustomAdapter(MainActivity.this, Languages));
btn.setOnClickListener(this);
spinner.setOnItemSelectedListener(this);
}
@Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
//item = (String)parent.getItemAtPosition(position);
item = (String) spinner.getSelectedItem().toString(); //Here is the Change
Toast.makeText(MainActivity.this, item.toString(),
Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
此处的更改为
来自
item = (String)parent.getItemAtPosition(position);
要
item = (String) spinner.getSelectedItem().toString();