If we want to delete a row of ListView, create a button name Delete row.
Declare an arraylist.
ArrayList<String> fru
= new ArrayList<String>();
Add elements in to arraylist.
fru.add("Pear");
fru.add("Banana");
fru.add("Cashew");
fru.add("Orange");
fru.add("Water
melon");
fru.add("Peach");
fru.add("Grape");
fru.add("Mango");
fru.add("Plum");im
After that, set adapter for ListView like this
adapter = new
ArrayAdapter<String>(forth.this,
android.R.layout.simple_list_item_checked,
fru);
Declare a variable name count=0, if user click on row, count=1
In the code of button Delete, check value of count, if count=0, show toast to request user click row, if count=1, delete row.
b1.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v)
{
if (count == 0) {
Toast.makeText(forth.this,"Please
choose one row", Toast.LENGTH_SHORT).show();
} else {
SparseBooleanArray checked = lv.getCheckedItemPositions();
for (int i = 0; i < lv.getCount();
i++) {
if (checked.get(i)
== true) {
qua2.remove(i);
}
adapter.notifyDataSetChanged();
}
lv.clearChoices();
}
}
});
Run to see the row disappear after click button Delete.
As we delete row but do nothing with arraylist fru,
so if we reopen, ListView still has all it’s lines.
To completely delete row, we have to change arraylist, see this post.
No comments:
Post a Comment