One of the first things that I wanted to try out was adding a checkbox to the simple notepad v1 application in the tutorial. The tutorial uses a SimpleCursorAdapter and then uses this in a call to setListAdapter to populate the screen with information from the database.
I added an extra checkbox to the notes_row as I wanted a checkbox to be displayed as well. Also, instead of using a LinearLayout, I used a RelativeLayout for each of the items in the list. The XML I used was as follow:
<?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" >
<TextView android:id="@+id/text1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignParentTop="true"
android:layout_alignParentLeft="true">
</TextView>
<CheckBox android:id="@+id/CheckBox1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="CheckBox"
android:layout_alignParentTop="true" android:layout_alignParentRight="true">
</CheckBox>
</RelativeLayout>
Note that I used this handy little
droid draw tool to generate the XML layout.
Now, I was ready to go with taking the data from the database and populating the text and checkbox - the problem is, how do I convert the data in the database to a checkbox format?
The answer is by using setViewBinder. Here is the code that I used:
private void fillData() {
Cursor c = mdbHelper.fetchAllNotes();
startManagingCursor(c);
String[] from = new String[] { NotesDbAdapter.KEY_TITLE, NotesDbAdapter.KEY_CHECK };
int[] to = new int[] { R.id.text1, R.id.CheckBox1 };
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter notes = new SimpleCursorAdapter(this, R.layout.notes_row, c, from, to);
notes.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
int nCheckedIndex = cursor.getColumnIndexOrThrow(NotesDbAdapter.KEY_CHECK);
if (columnIndex == nCheckedIndex) {
CheckBox cb = (CheckBox) view;
boolean bChecked = (cursor.getInt(nCheckedIndex) != 0);
cb.setChecked(bChecked);
return true;
}
return false;
}
});
setListAdapter(notes);
}
As data is retrieved from the database, the adapter sets the value on the view. If it is setting the value for the checkbox (as indicated by the columnIndex), we simply obtain the checkbox, set its state and return true. If we return false, the adapter will use its normal method to populate the UI element.