如何添加一个暗示,微调窗口小部件? [英] How can I add a hint to the Spinner widget?
问题描述
我有一个微调
在 spinnerMode =下拉
模式。取而代之的是preselected第一个项目,我想向用户显示一个提示,让没有默认的选择(如»请选择一个项目«)
I have a Spinner
in spinnerMode="dropdown"
mode. Instead of the preselected first item, I want to show the user a hint, so that there is no default selection (like »Please select an item«)
这是我得到的用户界面:
This is the UI I got:
这是我想才达到的用户界面:
and this is the UI I want to achive:
我想通了的EditText
小部件有一个安卓提示
属性,而不是微调
部件和设置它不会给我带来了我想要的UI。这是一款Android 4.x的 - 唯一的应用程序,这样我就不必麻烦地把任何pre-4.0兼容的东西。
I figured that the EditText
widget has an android:hint
attribute, but not the Spinner
widget and setting it doesn't bring me the the UI I want. This is an Android 4.x-only app, so I don't have to hassle with any pre-4.0 compatibility stuff.
推荐答案
我还没有找到一个简单而干净的解决方案还只是使用自定义的适配器和一个自定义项目类此解决方法:
I haven't found an easy and clean solution yet just this workaround using custom adapters and a custom item class:
首先,我们需要一个类微调项内容:
First, we need a class for the spinner item content:
class SpinnerItem {
private final String text;
private final boolean isHint;
public SpinnerItem(String strItem, boolean flag) {
this.isHint = flag;
this.text = strItem;
}
public String getItemString() {
return text;
}
public boolean isHint() {
return isHint;
}
}
那么,我们的适配器类:
Then our adapter class:
class MySpinnerAdapter extends ArrayAdapter<SpinnerItem> {
public MySpinnerAdapter(Context context, int resource, List<SpinnerItem> objects) {
super(context, resource, objects);
}
@Override
public int getCount() {
return super.getCount() - 1; // This makes the trick: do not show last item
}
@Override
public SpinnerItem getItem(int position) {
return super.getItem(position);
}
@Override
public long getItemId(int position) {
return super.getItemId(position);
}
}
最后,我们使用的解决方法是这样的:
Finally we use the workaround like this:
ArrayList<SpinnerItem> items = new ArrayList<SpinnerItem>();
items.add(new SpinnerItem("Item 1", false));
items.add(new SpinnerItem("Item 2", false));
items.add(new SpinnerItem("HINT", true)); // Last item
MySpinnerAdapter adapter = new MySpinnerAdapter(this, android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setSelection(items.size() - 1);
然后就可以使用该标志从SpinnerItem类设置文本颜色为项目或什么的。
Then you can use the flag from the SpinnerItem class to set text color for that item or whatever.
这篇关于如何添加一个暗示,微调窗口小部件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!