我一直在寻找这个问题。几天前我开始编码,我正在尝试创建一个动态列表视图,您可以通过选中复选框并删除选中的选项来添加字符串并将其删除。
此代码有效,但只有在从上到下检查多个项目时才能删除。如果我开始检查底部,然后检查顶部,它只删除顶部的一个。如果我从下到上检查所有方框,它会移除顶部和底部。如果我先检查中间的一个而不先检查其他内容,它会正确删除它。
请提供任何帮助。
public class Main3Activity extends AppCompatActivity {
ArrayList<String> questions = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
//listview
//add items
questions.add("Jag har aldrig");
questions.add("Jag har aldrig varit");
questions.add("Jag har aldrig2");
//Checkboxadapters
final ListView questionList = (ListView) findViewById(R.id.questionList);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, questions);
if(questionList != null) {
questionList.setAdapter(adapter);
questionList.setItemsCanFocus(false);
questionList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
/*questionList.setOnItemClickListener(new AdapterView.OnItemClickListener() { //LISTENER
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CheckedTextView ctv = (CheckedTextView)view;
if(ctv.isChecked()){
Toast.makeText(Main3Activity.this, "now it is checked", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(Main3Activity.this, "now it is unchecked", Toast.LENGTH_SHORT).show();
}
}
});*/
}
//Erasebutton listener
final Button eraseButton = (Button) findViewById(R.id.eraseButton);
assert eraseButton != null;
eraseButton.setOnClickListener(new View.OnClickListener() { //erasebutton onclick
public void onClick(View eraseButton) {
assert questionList != null;
SparseBooleanArray checked = questionList.getCheckedItemPositions();
for(int i=0; i < questionList.getCount(); i++)
{
if(checked.get(i)) {
//What to do with selected listitems
String item = (String) questionList.getAdapter().getItem(i);
Toast.makeText(Main3Activity.this, String.format("Removed: %s",item), Toast.LENGTH_SHORT).show();
adapter.remove(questions.get(i));
}
}
checked.clear();
adapter.notifyDataSetChanged();
}
});
//Nextbutton listener
final Button returnButton = (Button) findViewById(R.id.returnButton);
assert returnButton != null;
returnButton.setOnClickListener(new View.OnClickListener() { //Nextbutton onclick
public void onClick(View returnButton) {
Intent mainMenu = new Intent(Main3Activity.this, Main2Activity.class);
Main3Activity.this.startActivity(mainMenu);
}
});
}
}
答案 0 :(得分:3)
当您删除项目时,总计数更改和其他项目已移位,因此您的循环正确删除列表视图中的第一个选中项目。您可以尝试更改循环的方向:
for(int i = questionList.getCount() - 1; i >= 0; i--)
{
if(checked.get(i)) {
//What to do with selected listitems
String item = (String) questionList.getAdapter().getItem(i);
Toast.makeText(Main3Activity.this, String.format("Removed: %s",item), Toast.LENGTH_SHORT).show();
adapter.remove(questions.get(i));
}
}
说明你的循环如何运作: