Android ListView with CheckBox - The easy way

After MUCH Googling for a simple way to add a checkbox to a listview, I finally found an example in the ApiDemos that come with the SDK.

If your looking for this end outcome, then read on.

Auto Uploader

The "Enabled" with CheckBox above is actually a ListView, within a regular Activity, with just one item in the list.

First, simply add the ListView to your xml layout (main.xml):

<ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
</ListView>


Second, in your Activity, define a String[] of items (just one for me), and wire up the ListView into a variable. List so in my onCreate():


ListView listView1;
String[] listItems = { "Enabled" };

listView1 = (ListView)findViewById(R.id.listView1);

listView1.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, listItems));
listView1.setItemsCanFocus(false);
listView1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

Boom, thats it to make it show up in your Activity! Obviously, I also needed the "click" to work, so here's the code for the setOnItemClickListener():

listView1.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
CheckedTextView ctv = (CheckedTextView)arg1;
//do your stuff in here! 
}
});


Comments

  1. Thnx, worked like a charm :)

    ReplyDelete
  2. Worked for me as well, thank you very much!

    ReplyDelete
  3. Thank you very much for the code. He had seen several codes but all were very long.

    ReplyDelete
  4. Thank you very much for the code. He had seen several codes but all were very long.

    ReplyDelete
  5. Thanks for the example

    ReplyDelete

Post a Comment

Popular posts from this blog

Starting an Activity from ItemizedOverlay

WhoCalled