ListView with multiple choice

Hi Guys!!
Today i am sharing the code of the multiple choice option select in list view.
ListView is a view group that displays a list of scrollable items. The list items are automatically inserted to the list using an Adapter that pulls content from a source such as an array or database query and converts each item result into a view that's placed into the list. 

For more details about the List View visit the Android Developer site List View.

Lets Start the coding now.


activty_main.xml



    

    

MainActivity.java

package com.sunil.listview;

 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 MainActivity 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.activity_main);
        myList = (ListView)findViewById(R.id.list);
        getChoice = (Button)findViewById(R.id.getchoice);
 
        ArrayAdapter adapter = new ArrayAdapter(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) {
             
                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(MainActivity.this, selected, Toast.LENGTH_LONG).show();
 
            }});
 
    }
 
}

Please download the source code ListView with multiple choice

 Cheers Guys!!

2 comments:

Debug Database in Android

In my last tutorial, we have learned how we can use persistence database in android. We also understood which database wrapper we can use...

Contact Me

Name

Email *

Message *