Thursday 2 February 2012

Creating custom spinner for multiselection items


We can create a Spinner dynamically to show the items of spinner with
check boxes which can allow you to give multiple selection.
Steps for using the custom spinner in our class
created a custom class for spinner extending our class with Spinne class.
And used the spinner in our xml file as pre defined xml tag.

Create a custom spinner class
like

MultiSpinner.java

package cz.destil.settleup.gui;

import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.util.AttributeSet;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class MultiSpinner extends Spinner implements
        OnMultiChoiceClickListener, OnCancelListener {

    private List<String> items;
    private boolean[] selected;
    private String defaultText;
    private MultiSpinnerListener listener;
    int count=0;

    public MultiSpinner(Context context) {
        super(context);
    }

    public MultiSpinner(Context arg0, AttributeSet arg1) {
        super(arg0, arg1);
    }

    public MultiSpinner(Context arg0, AttributeSet arg1, int arg2) {
        super(arg0, arg1, arg2);
    }

    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
   
        if (isChecked)
            selected[which] = true;
        else
            selected[which] = false;
    }

    public void onCancel(DialogInterface dialog) {
        // refresh text on spinner
        StringBuffer spinnerBuffer = new StringBuffer();
        boolean someUnselected = false;
        for (int i = 0; i < items.size(); i++) {
            if (selected[i] == true) {
                spinnerBuffer.append(items.get(i));
                spinnerBuffer.append(", ");
               } else {
                someUnselected = true;
            }
        }
        String spinnerText;
        if (someUnselected) {
            spinnerText = spinnerBuffer.toString();
            //
            if(spinnerText.toString().length()==0){
            spinnerText="Not Selected";
            }
           //
            if (spinnerText.length() > 2){
                spinnerText = spinnerText.substring(0, spinnerText.length() - 2);
            }
        } else {
            spinnerText = defaultText;
        }
        //
        for(int i=0;i<selected.length;i++){
        if(selected[i]==true){
        System.out.println(i+" Count "+count);
        count=count++;
        }
        }
        if(count==items.size()){
        spinnerText="All Selected";
        System.out.println(" 66666666 ");
       
        }
        //
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),android.R.layout.simple_spinner_item,new String[] { spinnerText });
        setAdapter(adapter);
        listener.onItemsSelected(selected);
    }

    @Override
    public boolean performClick() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setMultiChoiceItems(items.toArray(new CharSequence[items.size()]), selected, this);
        builder.setPositiveButton("Ok",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
        builder.setOnCancelListener(this);
        builder.show();
        return true;
    }

    public void setItems(List<String> items, String allText,MultiSpinnerListener listener) {
        this.items = items;
        this.defaultText = allText;
        this.listener = listener;

        // all unselected by default
        selected = new boolean[items.size()];
        for (int i = 0; i < selected.length; i++)
            selected[i] = false;
        // all text on the spinner
       
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),android.R.layout.simple_spinner_item, new String[] { allText });
        setAdapter(adapter);
    }

    public interface MultiSpinnerListener {
        public void onItemsSelected(boolean[] selected);  
    }
}

and use it in xml file like

<cz.destil.settleup.gui.MultiSpinner android:id="@+id/multi_spinner" android:layout_width="fill_parent"
    android:layout_height="wrap_content" />


and used it in main activity class as same as common spinner  MyClass.java



package cz.destil.settleup.gui;

import java.util.ArrayList;
import java.util.List;

import cz.destil.settleup.gui.MultiSpinner.MultiSpinnerListener;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;

public class MyClass extends Activity  implements MultiSpinnerListener{
    /** Called when the activity is first created. */
int[] selectedItems={0,0,0};
ArrayList al;
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        String[] arr={"Raghu","Ram","Reddy"};
     
       al=new ArrayList();
        al.add("raghu");
        al.add("ram");
        al.add("reddy");
        MultiSpinner multiSpinner = (MultiSpinner) findViewById(R.id.multi_spinner);
       
        multiSpinner.setItems(al, "Select",MyClass.this);
       
        multiSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){

@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub

}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub

}});
    }

@Override
public void onItemsSelected(boolean[] selected) {
for(int i=0;i<selected.length;i++){
if(selected[i]){
selectedItems[i]=1;
// System.out.println("______________________"+al.get(i));
}
else selectedItems[i]=0;
}
for(int i=0;i<selectedItems.length;i++){
// if(selectedItems[i]==1)
// System.out.println(al.get(i));
}
}
   
}

No comments:

Post a Comment