巴拉克的解决方案有问题.当您选择第一个项目时,Spinner将不会调用OnItemSelectedListener的onItemSelected()并刷新空内容,因为前一个位置和选择位置都为0.
首先在字符串数组的开头放一个空字符串:
String[] test = {" ", "one", "two", "three"};
第二个构建适配器,不要修改getView(),修改getDropDownView().将空视图的高度设置为1px.
public class MyArrayAdapter extends ArrayAdapter {
private static final int ITEM_HEIGHT = ViewGroup.LayoutParams.WRAP_CONTENT;
private int textViewResourceId;
public MyArrayAdapter(Context context,
int textViewResourceId,
String[] objects) {
super(context, textViewResourceId, objects);
this.textViewResourceId = textViewResourceId;
}
@Override
public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) {
TextView textView;
if (convertView == null) {
textView = (TextView) LayoutInflater.from(getContext())
.inflate(textViewResourceId, parent, false);
} else {
textView = (TextView) convertView;
}
textView.setText(getItem(position));
if (position == 0) {
ViewGroup.LayoutParams layoutParams = textView.getLayoutParams();
layoutParams.height = 1;
textView.setLayoutParams(layoutParams);
} else {
ViewGroup.LayoutParams layoutParams = textView.getLayoutParams();
layoutParams.height = ITEM_HEIGHT;
textView.setLayoutParams(layoutParams);
}
return textView;
}
}