ListView [ List An Array with Multiplce Choices and Display Selections ]

In this post, we will be learning how we can make use of ListView Object in Android to list the array, allows user to make multiple selections and display the selected items. This could be useful if you are sending a bulk messages to a group of friends from your contact list.

This application is developed in Eclipse IDE. After creating a new project, change your main.xml (it is located at ./res/layout) into below codes.








Now, change your java code to below.
package edu.mobilestudent.extractContact;

import android.app.Activity;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class Main extends Activity {  
 TextView selection;
 ListView iView;
 String[] os={"window xp","window vista","linux","unix","mac","ubuntu"};
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        iView=(ListView)findViewById(R.id.list);
        selection=(TextView)findViewById(R.id.selection);
        
        iView.setAdapter(new ArrayAdapter(this,android.R.layout.simple_list_item_multiple_choice,os));
        iView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        
        iView.setOnItemClickListener(new OnItemClickListener(){
          @Override
          public void onItemClick(AdapterView parent, View v, int pos, long id) {
            selection.setText("");
            int len = iView.getCount();
            SparseBooleanArray checked = iView.getCheckedItemPositions();
            for (int i=0; i<len; i++){
             if (checked.valueAt(i)){
              selection.append(os[checked.keyAt(i)]+" ");
             }
            }    
          }
        });
   }
}
With the changes in both main.xml and your java file, run your application.