我有一个微调器,它显示一些值(单击之前),并且我想使其不显示任何值,直到用户单击它为止。我该怎么做?
答案 0 :(得分:1)
执行此操作的一种简单方法是,将一个空值添加为微调器数组的第一个值,然后在继续之前检查非空值。假设您的数组中没有其他预期的空值。
在array.xml文件中:
<resources>
<string-array name="spinner_options">
<item> </item>
<item>one</item>
<item>two</item>
<item>three</item>
<item>four</item>
<item>five</item>
</string-array>
</resources>
在显示微调框的活动中:
private Spinner mSpinner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSpinner = (Spinner) findViewById(R.id.spinner_type);
//set array to array adapter
ArrayAdapter typeSpinnerAdapter = ArrayAdapter.createFromResource(this,
R.array.spinner_options, android.R.layout.simple_spinner_item);
typeSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
//set adapter to spinner view
mSpinner.setAdapter(typeSpinnerAdapter);
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selection = (String) parent.getItemAtPosition(position);
if (TextUtils.isEmpty(selection)) {
//show toast prompting user to select item from spinner
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
//show toast prompting user to select item from spinner
}
});
如果您需要一个更强大的解决方案,允许选择为空字符串,这里How to set Spinner default value to null?
谢谢