我的应用中有一个微调器,带有自定义适配器。我面临的问题是:在打开微调器下拉菜单并关闭它而不选择任何项目时,即使我没有选择任何微调器项目,第一个微调器项目也会被选中。
所以,简单来说就是在简单地打开和关闭微调器下拉列表而不选择任何项目之后,如果我调用spinner.getselecteditem.getText.toString
,它将返回第一个微调器项。
下面我发布了我的代码:
按下按钮:
CustomSpinnerAdapterVertical customSpinnerAdapterVerticalMarket = new CustomSpinnerAdapterVertical(myContext,
R.layout.vertical_spinner_row, alst_verticalMarket, "Select Vertical Market");
vertical_spinner.setAdapter(customSpinnerAdapterVerticalMarket);
对于CustomSpinnerAdapterVertical:
class CustomSpinnerAdapterVertical extends ArrayAdapter<String> {
Context context;
ArrayList<String> objects;
String firstElement;
boolean isFirstTime;
public CustomSpinnerAdapterVertical(Context context, int textViewResourceId, ArrayList<String> objects, String defaultText) {
super(context, textViewResourceId, objects);
this.context = context;
this.objects = objects;
this.isFirstTime = true;
setDefaultText(defaultText);
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
if(isFirstTime) {
objects.set(0, firstElement);
isFirstTime = false;
}
return getCustomDropdownView(position, convertView, parent);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
notifyDataSetChanged();
return getCustomView(position, convertView, parent);
}
public void setDefaultText(String defaultText) {
this.firstElement = objects.get(0);
objects.set(0,defaultText);
}
public View getCustomView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.vertical_spinner_row, parent, false);
TextView label = (TextView) row.findViewById(R.id.spinnerText);
label.setText(objects.get(position));
return row;
}
public View getCustomDropdownView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.simple_spinner_dropdown_vertical_item, parent, false);
CheckedTextView label = (CheckedTextView) row.findViewById(R.id.text1);
label.setText(objects.get(position));
return row;
}
}
我有什么遗漏或做错了吗?