具有空默认选定项目的微调器 [英] Spinner with empty default selected item
问题描述
我正在尝试使用默认的空选定项创建一个微调器,但它显示了微调器选项中的第一个项目。如果我将空值添加到我的字符串(这是spinner中的选择源),则在打开微调器后显示空行。我该怎么办?这是我正在使用的代码:
I'm trying to create a spinner with default empty selected item, but it displays the first item from the choices of spinner. If I add null value to my string, which is the source of choices in spinner, then after opening spinner that empty row is displayed. How should I do it? Here's code I'm using:
String[] ch = {"Session1", "Session2", "Session3"};
Spinner sp = (Spinner)findViewById(R.id.spinner1);
TextView sess_name = findViewById(R.id.sessname);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,ch);
sp.setAdapter(adapter);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener({
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
int index = arg0.getSelectedItemPosition();
sess_name.setText(ch[index]);
Toast.makeText(getBaseContext(), "You have selected item : " + ch[index], Toast.LENGTH_SHORT).show();
}
推荐答案
Barak的解决方案有问题。当您选择第一项时,Spinner不会调用OnItemSelectedListener的 onItemSelected()
并刷新空内容,因为之前的位置和选择位置都是0.
Barak's solution have a problem. When you select the first item, Spinner won't call OnItemSelectedListener's onItemSelected()
and refresh the empty content because the previous position and selection position both is 0.
首先在字符串数组的开头放一个空字符串:
First put a empty string at the begin of your string array:
String[] test = {" ", "one", "two", "three"};
第二个构建适配器,不要修改 getView()
,modi fy getDropDownView()
。将空View的高度设置为1px。
Second build adapter, don't modify getView()
, modify getDropDownView()
. Set the empty View's height to 1px.
public class MyArrayAdapter extends ArrayAdapter<String> {
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;
}
}
这篇关于具有空默认选定项目的微调器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!