I've searched around for this problem. I started coding some days ago and I'm trying to create a dynamic listview where you can add strings and remove them by checking checkboxes and removing checked options.
This code works, however it can only remove multiple items if they're checked from top to bottom. If I start checking the bottom one, and then check the top one, application crashes.
Please provide any help you can.
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);
}
});
}
}
Aucun commentaire:
Enregistrer un commentaire