Custom Data Adapters with Checked List Views – Part I

This entry is part 40 of 50 in the series Android Development Primer

We have been using ArrayAdapter and SimpleCursorAdapter while populating our List View with elements from an array and a database respectively. It is worth knowing that both these classes are subclasses of the DataAdapter class. The DataAdapter class is the primary class that allows for such adaptation and display of data.
Also, we have used simple List Views. On many occasions you would have seen List Views with checkboxes, that allow for multiple options to be selected.

This post along with the next, will show you how to do this. We will be using a custom Data Adapter with a List View containing checkbox. Remember that in Part I of this post I will show you how to create the Front End of the Activity, i.e. how to program the layout and the corresponding Java file for this activity. In the next post I will show you how to create the Custom Adapter in order for the Activity to work as decided. This can be a little complicated and is the sole reason I will be breaking it into two different posts. Complete Source Code is at the bottom.

  • Create a layout of the type CheckedTextView and paste the code below, there.
  • Create a layout for the Activity and insert 1 Edit Text and 7 Text Views in it. Also insert a button at the bottom. We will have the weekdays as our List View Items.
  • The button will trigger whatever you want to do with the selected items – whether you want to switch over to the next activity or finish the activity etc.
  • We will be creating something resembling a course schedule.
  • Switch over to the Java file and copy-paste the code from the Complete Source Code below.
  • Since the source code is complicated, I provide explanations below. If you fail to understand something, the next post will answer your questions.

Understanding the Code

  • I have used an ArrayList¬†instead of a simple array. For those who are unfamiliar with this class, it provides a linked implementation for Double Dimensional arrays.
  • The initialize() method adds weekdays to the ArrayList.
  • lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE) –¬†This statement is responsible for the checkboxes. If we wanted radio buttons, all we need to do is replace CHOICE_MODE_MULTIPLE with CHOICE_MODE_SINGLE.
  • We then, set the Adapter and define the onClick() method for the button.

COMPLETE SOURCE CODE

row_item.xml

<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/checkedtextview"
    android:layout_width="fill_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"
    android:checkMark="?android:attr/listChoiceIndicatorMultiple"
    android:gravity="center_vertical"
    android:orientation="vertical"
    android:paddingBottom="10dip"
    android:paddingLeft="20dip"
    android:paddingRight="20dip"
    android:paddingTop="10dip"
    android:textColor="#000000"

    android:onClick="toggle"
    >

</CheckedTextView>

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:background="#D0D0D0" >

    <Button
        android:id="@+id/addcourse"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="Go" />
    
    <EditText
        android:id="@+id/coursenameet"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:layout_marginBottom="2dp"
        android:layout_marginTop="2dp"
        android:hint="Course Name" 
        android:inputType="textCapWords" >

    </EditText>
    
    <View
        android:id="@+id/divider"
        android:layout_width="match_parent"
        android:layout_height="3dp"
        android:layout_below="@+id/coursenameet"
        android:layout_marginBottom="5dp"
        android:layout_marginTop="5dp"
        android:background="@android:color/darker_gray" >
    </View>
    
    <TextView
        android:id="@+id/weekdaytv"
        android:layout_width="wrap_content"
		android:layout_height="wrap_content"
        android:layout_below="@+id/divider"
        android:layout_marginBottom="3dp"
        android:layout_marginTop="3dp"
        android:layout_centerHorizontal="true"
        android:text="Select weekdays for this Course" >
    </TextView>
    
    <RelativeLayout 
    	android:id="@+id/rlinner"
    	android:layout_width="match_parent"
    	android:layout_height="match_parent"
    	android:layout_centerVertical="true"
    	android:layout_centerHorizontal="true"  
    	android:layout_above="@+id/addcourse"
	    android:layout_below="@+id/weekdaytv">
	    
        <RelativeLayout 
	    	android:id="@+id/rlinnermost"
	    	android:layout_width="match_parent"
	    	android:layout_height="wrap_content"
	    	android:layout_centerVertical="true"
	    	android:layout_centerHorizontal="true" >
    	
		    <ListView
		        android:id="@+id/listView1"
		        android:layout_width="match_parent"
		        android:layout_height="wrap_content"
		        android:divider="#FFFFFF"
		    	android:dividerHeight="2dp" />
	    </RelativeLayout>
    	
	</RelativeLayout>

</RelativeLayout>

MainActivity.java

package com.nero.myfirstapp;

import java.util.ArrayList;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class Main extends Activity {
	ArrayList weekdays = new ArrayList();
	ArrayList ret = new ArrayList();
	ListView lv;
	EditText coursename;
	Button addcourse;
	Adapter adapter;
	String c;
	long courseid;

	public void initialize(){
		weekdays.add("Monday");weekdays.add("Tuesday");weekdays.add("Wednesday");
		weekdays.add("Thursday");weekdays.add("Friday");weekdays.add("Saturday");
	}

	public void getoldweekdays(long id){
		ret.clear();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		ret.clear();
		initialize();
		lv = (ListView) findViewById(R.id.listView1);
		coursename = (EditText) findViewById(R.id.coursenameet);
		addcourse = (Button) findViewById(R.id.addcourse);
		lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

		courseid = getIntent().getLongExtra("courseid", -1);
		adapter = new Adapter(this, R.layout.row_item, R.id.checkedtextview, weekdays);
		lv.setAdapter(adapter);
		for(int i=0;i<ret.size();i++)lv.setItemChecked(ret.get(i), true);

		lv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,	long id) {
				adapter.toggle(position);
			}
		});

		addcourse.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				ArrayList checkeditem = adapter.getCheckedItems();
				finish();
			}
		});
	}
}
Series Navigation<< Context Menus is List View using Simple Cursor AdapterCustom Data Adapters with Checked List Views – Part II >>

Leave a Reply

Your email address will not be published. Required fields are marked *

*

* Copy This Password *

* Type Or Paste Password Here *

42,383 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>