微调工具的代码如下所示,我的应用程序中的微调工具有时会出于某种奇怪的原因复制它的内容。如何防止这种情况发生?:
Spinner spinnerG = (Spinner) findViewById(R.id.spGroup);
final ArrayAdapter<String> dataAdapterG = new ArrayAdapter<>
(this, R.layout.simple_spinner_item, groups);
dataAdapterG.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
spinnerG.setAdapter(dataAdapterG); //general basics //sets up the group spinner, filled with the groups list
spinnerG.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
selectedGroup = groups.get(position);
studentsToShow.clear();
for(int i = 0; i < studList.size(); i++){
if(studList.get(i).getGroup().equals(selectedGroup)){
Students a = new Students();
a.setFirstName(studList.get(i).getFirstName());
a.setLastName(studList.get(i).getLastName());
a.setStudentID(studList.get(i).getStudentID());
a.setGroup(studList.get(i).getGroup());
studentsToShow.add(a); //when a new group is chosen the list of students in the selected group needs to be updated
} //this re uses the code earlier to make a list of student in the selected group
}
updateSpS(); //updates the student spinner
}
public void onNothingSelected(AdapterView<?> parent){
}
});
发布于 2018-07-11 10:03:14
如果您已放置此oncreate
事件,则微调器将复制。将微调填充代码放在onResume
方法上。
发布于 2018-07-11 10:13:04
从与问题分享的代码片段中,很难猜测为什么OP会有重复值。有根据的猜测是他的onItemSelected()被多次调用。
Spinner的(在我个人看来,是最糟糕的安卓小部件之一) onItemSelected()
可以因为不同的原因被调用多次,其中一件事我建议尝试这种方式-
class SpinnerInteractionListener implements AdapterView.OnItemSelectedListener, View.OnTouchListener {
boolean userSelect = false;
@Override
public boolean onTouch(View v, MotionEvent event) {
userSelect = true;
return false;
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (userSelect) {
// Your selection handling code here
userSelect = false;
if(view!=null){
selectedGroup = groups.get(position);
studentsToShow.clear();
for(int i = 0; i < studList.size(); i++){
if(studList.get(i).getGroup().equals(selectedGroup)){
Students a = new Students();
a.setFirstName(studList.get(i).getFirstName());
a.setLastName(studList.get(i).getLastName());
a.setStudentID(studList.get(i).getStudentID());
a.setGroup(studList.get(i).getGroup());
studentsToShow.add(a); //when a new group is chosen the list of students in the selected group needs to be updated
} //this re uses the code earlier to make a list of student in the selected group
}
updateSpS(); //updates the student spinner
}
}
}
}
然后设置-
SpinnerInteractionListener listener = new SpinnerInteractionListener();
spinnerG.setOnTouchListener(listener);
spinnerG.setOnItemSelectedListener(listener);
同时,这会在没有用户接触的情况下处理onItemSelected()的不必要的回调,如果之前有任何泄漏的侦听器的话。
https://stackoverflow.com/questions/51275407
复制相似问题