也许是一个奇怪的问题。我有两个spinners
,两个都来自同一list
的值。最初,我将它们设置到不同的位置。我需要它们总是不同的,即用户永远不能在第一个Spinner
中选择已在第二个中选择的String
,反之亦然。我能想到的最简单的方法是:
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
if (position == spinner2.getSelectedItemPosition()){
//UNDO OR CANCEL THE SELECTION SOMEHOW
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
问题是如何撤消对前一个微调器的选择?是否可以不保留全局变量?谢谢
答案 0 :(得分:0)
你可以使用Stack:
Stack<Integer> stack = new Stack<>();
boolean programaticalyChange = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
//Here initialize all you need
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (programaticalyChange) {
programaticalyChange = false;
} else {
stack.push(position);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {}
});
//I use button to pop stack back, but you can use any callback from second spinner
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
programaticalyChange = true;
if (queue.isEmpty()) {
//no backstack available
sp.setSelection(0);
} else {
if (queue.peek() == sp.getSelectedItemPosition()) queue.pop();
sp.setSelection(queue.pop());
}
}
});
}
答案 1 :(得分:0)
在if条件获取某个变量中之前选择的项目之前,如果条件为真,则使用此变量撤消选择。