I am new to Android, I am trying to do a simple application where in I have to display a list of contacts available in phonebook in a ListView in the application, I am tryring to add checkbox t each item. When the user checks the checkbox, I want to retrive the item. So far, I am able to display the list but its unclear how to check for the checkbox check event.
My code is as follows:
XML files:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ListView
android:id="@android:id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight = "1"
android:choiceMode="multipleChoice" android:clickable="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id ="@+id/savebutton"
android:text = "save"
/>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ListView
android:id="@android:id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight = "1"
android:choiceMode="multipleChoice" android:clickable="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id ="@+id/savebutton"
android:text = "save"
/>
</LinearLayout>
Source Code:
public class testcontacts extends ListActivity
{
private ListAdapter adapter = null;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//CheckBox box = (CheckBox)findViewById(R.id.checkbox);
//box.setFocusable(false);
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
adapter = new SimpleCursorAdapter
(this, R.layout.contact_entry, cur,new String[] {ContactsContract.Contacts.DISPLAY_NAME}, new int[] {R.id.contactEntryText});
setListAdapter(adapter);
ListView list = getListView();
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
}
You can use the getCheckedItemPosition method to get the position of the item that is checked.Once you have the position,you can use the findViewById to retrieve the item and the isChecked method to check.
Here’s an example :
Hope it helped.