我有一个Material Spinner,它显示图像和文本,但我只想检索OnItemSelected中的文本。但它返回null。
我的适配器类
public class SpinnerCustomAdapter extends BaseAdapter {
Context context;
int cat_pics[];
ArrayList<String> categoryNames;
LayoutInflater inflter;
public SpinnerCustomAdapter(Context applicationContext, int[] cat_pics, ArrayList<String> categoryNames) {
this.context = applicationContext;
this.cat_pics = cat_pics;
this.categoryNames = categoryNames;
inflter = (LayoutInflater.from(applicationContext));
}
@Override
public int getCount() {
return cat_pics.length;
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.custom_spinner_items, null);
ImageView icon = (ImageView) view.findViewById(R.id.imageView);
TextView names = (TextView) view.findViewById(R.id.textView);
icon.setImageResource(cat_pics[i]);
names.setText(categoryNames.get(i));
return view;
}
}
在主要活动中设置适配器
customAdapter=newSpinnerCustomAdapter(getApplicationContext(),cat_pics,allCatNames);
spCategories.setAdapter(customAdapter);
spCategories.setOnItemSelectedListener(this);
onItemSelected
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(parent.getContext(), "Selected Item : " + customAdapter.getItem(position) ,
Toast.LENGTH_LONG).show();
}
答案 0 :(得分:1)
在SpinnerCustomAdapter
中,您的getItem()
方法会返回null
@Override
public Object getItem(int i) {
return null;
}
更新getItem()
方法,如下所示:
@Override
public Object getItem(int i) {
return categoryNames.get(i);
}
#。您还可以使用parent.getItemAtPosition(position)
来选择item
。
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Selected Item : "
+ parent.getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show();
}
答案 1 :(得分:0)
尝试以下方法:
spinner.getSelectedItem().toString()
(OR) 在OnItemSelectedListener中:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Log.d("SeletedItem",adapterView.getSelectedItem().toString());
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
答案 2 :(得分:0)
试试这样,可以帮到你
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String text = spinner.getItemAtPosition(i)
Toast.makeText(getApplicationContext(), "Selected : " text, Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});