Saturday, 4 April 2015

Delete Items from Listview By ticking them using a checkbox



1. MainActivity.java

public class MainActivity extends ListActivity  {
EditText addtext;
ListView listview;
ArrayList<String> itemlist = new ArrayList<String>();
ArrayAdapter<String> adapter;

Button add,del;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intiViews();

}

private void intiViews(){
add = (Button) findViewById(R.id.btnAdd);
del = (Button) findViewById(R.id.btnDel);
addtext = (EditText) findViewById(R.id.txtItem);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, itemlist);

add.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
itemlist.add(addtext.getText().toString());
addtext.setText("");
adapter.notifyDataSetChanged();

}
});

del.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
SparseBooleanArray res = getListView()
.getCheckedItemPositions();
int itemCount = getListView().getCount();

for (int i = itemCount - 1; i >= 0; i--) {
if (res.get(i)) {
adapter.remove(itemlist.get(i));
}
}
res.clear();
adapter.notifyDataSetChanged();
}

});
setListAdapter(adapter);
}

}

2. activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/txtItem"
        android:layout_width="240dp"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:hint="Enter Country"
    />

    <Button
        android:id="@+id/btnAdd"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Add"
        android:layout_toRightOf="@id/txtItem"
    />

    <TextView
        android:id="@android:id/empty"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/txtItem"
        android:text="empty"
        android:gravity="center_horizontal"
    />

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/txtItem"
        android:choiceMode="multipleChoice" >
    </ListView>

    <Button
        android:id="@+id/btnDel"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="Delete Selected Items" />
</RelativeLayout>

Output :


2 comments: