Sep 2, 2011

ListView with multiple choice

ListView with multiple choice


package com.AndroidListView;


import android.app.Activity;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class AndroidListViewActivity extends Activity {

ListView myList;
Button getChoice;

String[] listContent = {
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
};

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myList = (ListView)findViewById(R.id.list);
getChoice = (Button)findViewById(R.id.getchoice);

ArrayAdapter<String> adapter
= new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice,
listContent);

myList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
myList.setAdapter(adapter);

getChoice.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

String selected = "";

int cntChoice = myList.getCount();
SparseBooleanArray sparseBooleanArray = myList.getCheckedItemPositions();
for(int i = 0; i < cntChoice; i++){
if(sparseBooleanArray.get(i)) {
selected += myList.getItemAtPosition(i).toString() + "\n";

}
}

Toast.makeText(AndroidListViewActivity.this,
selected,
Toast.LENGTH_LONG).show();
}});

}
}


<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/getchoice"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Get Choice"
/>
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>





5 comments:

  1. thanks for this! It helps me. God bless you!

    ReplyDelete
  2. y thr is not any code for adding check boxx

    ReplyDelete
    Replies
    1. .@Pradeep:
      the check boxes are automatically added when the adapter was created and bounded to the list, like this:

      android.R.layout.SIMPLE_LIST_ITEM_MULTIPLE_CHOICE
      if you will check again the code above you will notice that.
      the part that I capitalized set the checkbox.

      if you want only one choice you can set that like this:
      android.R.layout.SIMPLE_LIST_ITEM_1

      this tutorial IS VERY GOOD actually, big applause for the tutor!

      Delete
    2. @broJins:
      hey,
      If I want to change that boxes design, what to do for that? Please help me;

      Delete

Infolinks In Text Ads