好的,在 David 和 Felix 的回答的帮助下,我想我已经为自己的情况想出了一个解决方案(我相信 David 帮助了 Felix,这反过来又帮助了我)。我想我会将它与代码示例一起发布在这里,以防其他人发现这种方法也很有用。它还解决了我的两个问题(不需要的自动选择和所需的重新选择触发器)。
我所做的是添加一个“请选择”虚拟项目作为我列表中的第一项(最初只是为了解决自动选择问题,以便我可以在选择时忽略它没有用户交互),然后,选择另一个另一个 em>项目并且我处理了选择时,我简单地重置 em>旋转器到虚拟项目(忽略)。想一想,在决定在这个网站上发布我的问题之前,我早就应该想到这一点,但事后看来,事情总是更明显......我发现写我的问题实际上帮助我思考了什么我想实现。
显然,如果有一个虚拟项目不适合您的情况,这可能不是您的理想解决方案,但因为我想要的是在用户选择一个值时触发一个操作(并且让该值保持选中状态)在我的特定情况下不需要),这很好用。我将尝试在下面添加一个简化的代码示例(可能无法按原样编译,我已经从我的工作代码中删除了一些内容并在粘贴之前重命名了一些内容,但希望你能明白这一点)。
首先,包含微调器的列表活动(在我的例子中),我们称之为 MyListActivity:
public class MyListActivity extends ListActivity {
private Spinner mySpinner;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO: other code as required...
mySpinner = (Spinner) findViewById(R.id.mySpinner);
mySpinner.setAdapter(new MySpinnerAdapter(this));
mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> aParentView,
View aView, int aPosition, long anId) {
if (aPosition == 0) {
Log.d(getClass().getName(), "Ignoring selection of dummy list item...");
} else {
Log.d(getClass().getName(), "Handling selection of actual list item...");
// TODO: insert code to handle selection
resetSelection();
}
}
@Override
public void onNothingSelected(AdapterView<?> anAdapterView) {
// do nothing
}
});
}
/**
* Reset the filter spinner selection to 0 - which is ignored in
* onItemSelected() - so that a subsequent selection of another item is
* triggered, regardless of whether it's the same item that was selected
* previously.
*/
protected void resetSelection() {
Log.d(getClass().getName(), "Resetting selection to 0 (i.e. 'please select' item).");
mySpinner.setSelection(0);
}
}
微调器适配器代码可能看起来像这样(如果您愿意,实际上可以是上述列表活动中的内部类):
public class MySpinnerAdapter extends BaseAdapter implements SpinnerAdapter {
private List<MyListItem> items; // replace MyListItem with your model object type
private Context context;
public MySpinnerAdapter(Context aContext) {
context = aContext;
items = new ArrayList<MyListItem>();
items.add(null); // add first dummy item - selection of this will be ignored
// TODO: add other items;
}
@Override
public int getCount() {
return items.size();
}
@Override
public Object getItem(int aPosition) {
return items.get(aPosition);
}
@Override
public long getItemId(int aPosition) {
return aPosition;
}
@Override
public View getView(int aPosition, View aView, ViewGroup aParent) {
TextView text = new TextView(context);
if (aPosition == 0) {
text.setText("-- Please select --"); // text for first dummy item
} else {
text.setText(items.get(aPosition).toString());
// or use whatever model attribute you'd like displayed instead of toString()
}
return text;
}
}
我想(没有尝试过)使用setSelected(false) 而不是setSelection(0) 可以达到相同的效果,但是重新设置为“请选择”很适合我的目的。而且,“看,妈,没有旗帜!” (虽然我猜忽略 0 的选择并没有那么不同。)
希望这可以帮助其他有类似用例的人。 :-) 对于其他用例,Felix 的回答可能更合适(感谢 Felix!)。