我正在寻找一种方法,以隐藏一个项目在一个 Android 旋转小部件。这将允许您模拟一个没有选择任何项目的微调器,并确保对选中的每个项目(如果隐藏项目是“当前”项目)始终调用 onItemSelected ()回调。通常,在 spinner 中总有一个项目不会生成回调,即当前项目。
有一些关于 stackoverflow 的代码可以用来禁用(灰度)项,但是不能用来完全隐藏项,就好像它们不存在一样。
经过大量的实验,我想出了一个有点黑客风格的解决方案,可以在各种新旧 Android 平台上运行。它有一些很难注意到的外观上的小缺点。我仍然希望听到一个更正式的解决方案,而不是“不要用旋转器”。
这总是隐藏微调器中的第一个项目,但是可以相当容易地扩展以隐藏任意项目或多个项目。在 spinner 项列表的开头添加一个包含空字符串的虚拟项。您可能希望在旋转器对话框打开之前将当前的旋转器选择设置为项0,这将模拟未选择的旋转器。
具有 ArrayAdapter 方法覆盖的旋转器设置示例:
List<String> list = new ArrayList<String>();
list.add(""); // Initial dummy entry
list.add("string1");
list.add("string2");
list.add("string3");
// Populate the spinner using a customized ArrayAdapter that hides the first (dummy) entry
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list) {
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
View v = null;
// If this is the initial dummy entry, make it hidden
if (position == 0) {
TextView tv = new TextView(getContext());
tv.setHeight(0);
tv.setVisibility(View.GONE);
v = tv;
}
else {
// Pass convertView as null to prevent reuse of special case views
v = super.getDropDownView(position, null, parent);
}
// Hide scroll bar because it appears sometimes unnecessarily, this does not prevent scrolling
parent.setVerticalScrollBarEnabled(false);
return v;
}
};
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(dataAdapter);