经过一番思考,我相信我已经想出了实现您目标的方法。它涉及创建自定义适配器并设置/维护标志以确定是否选择了微调器中的项目。使用此方法,您无需创建/使用错误数据(您的空字符串)。
基本上,适配器getView
方法为关闭的微调器设置文本。因此,如果您覆盖它并在那里设置条件,您可以在启动时有一个空白字段,并且在您做出选择后,它会出现在关闭的微调框中。唯一需要记住的是,当您需要查看关闭的微调器中的值时,您需要设置标志。
我创建了一个小示例程序(下面的代码)。
请注意,我只添加了示例所需的单个构造函数。您可以实现所有标准的 ArrayAdapter 构造函数,也可以只实现您需要的那些。
SpinnerTest.java
public class SpinnerTestActivity extends Activity {
private String[] planets = { "Mercury", "Venus", "Earth", "Mars",
"Jupiter", "Saturn", "Uranus", "Neptune" };
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
CustomAdapter adapter = new CustomAdapter(this, // Use our custom adapter
android.R.layout.simple_spinner_item, planets);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
CustomAdapter.flag = true; // Set adapter flag that something
has been chosen
}
});
}
}
CustomAdapter.java
public class CustomAdapter extends ArrayAdapter {
private Context context;
private int textViewResourceId;
private String[] objects;
public static boolean flag = false;
public CustomAdapter(Context context, int textViewResourceId,
String[] objects) {
super(context, textViewResourceId, objects);
this.context = context;
this.textViewResourceId = textViewResourceId;
this.objects = objects;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = View.inflate(context, textViewResourceId, null);
if (flag != false) {
TextView tv = (TextView) convertView;
tv.setText(objects[position]);
}
return convertView;
}
}