Skip to content Skip to sidebar Skip to footer

Android Spinner - How To Default List Selection To None

I have an Android form that needs to update itself based on certain selections. The form is currently made up of 2 Spinners (A and B). Spinner B not created until Spinner A's selec

Solution 1:

My data-sizes.xml:

<?xml version="1.0" encoding="utf-8"?><resources><string-arrayname="chunks"><item>2</item><item>4</item><item>8</item><item>16</item><item>32</item></string-array></resources>

In main.xml:

<Spinner android:id="@+id/spinnerSize"android:layout_marginLeft="50px"android:layout_width="fill_parent"android:drawSelectorOnTop="true"android:layout_marginTop="5dip"android:prompt="@string/SelectSize"android:layout_marginRight="30px"android:layout_height="35px" /> 

In Java Code:

Spinner spinnerSize;
ArrayAdapter adapter;

...

spinnerSize = (Spinner)findViewById(R.id.spinnerSize);
adapter = ArrayAdapter.createFromResource(this, R.array.chunks, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSize.setAdapter(adapter);
spinnerSize.setOnItemSelectedListener(newMyOnItemSelectedListener());

...

classMyOnItemSelectedListenerimplementsOnItemSelectedListener {

    publicvoidonItemSelected(AdapterView<?> parent,
        View view, int pos, long id) {
        chunkSize = newInteger(parent.getItemAtPosition(pos).toString()).intValue();
    }
    publicvoidonNothingSelected(AdapterView<?> parent) {
      // Dummy
    }
}

So, although I can see 2 as my first default item, nothing happens unless user actually selects it.

Hope this helps!

Solution 2:

If you want, there is a decorater spinnerAdapter witch add automatically a default value :

protectedclassSpinnerAdapterWithNoValueimplementsSpinnerAdapter {

        private SpinnerAdapter _current;
        privatefinalstaticStringdefaultValue="Choisir";

        publicSpinnerAdapterWithNoValue(SpinnerAdapter base) {
            _current = base;
        }

        @OverridepublicintgetCount() {
            return _current.getCount() + 1;
        }

        @Overridepublic Object getItem(int position) {
            if (position == 0 || position == -1) {
                returnnull;
            }
            return _current.getItem(position - 1);
        }

        @OverridepubliclonggetItemId(int position) {
            if (position == 0 || position == -1) {
                return -1;
            }
            return _current.getItemId(position - 1);
        }

        @OverridepublicintgetItemViewType(int position) {
            if (position == 0 || position == -1) {
                return -1;
            }
            return _current.getItemViewType(position - 1);
        }

        @Overridepublic View getView(int position, View convertView, ViewGroup parent) {
            if (position == 0 || position == -1) {
                finalTextViewv= (TextView) ((LayoutInflater) getContext().getSystemService(
                        Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.spinner_text, parent, false);
                v.setText(defaultValue);
                return v;
            }
            return _current.getView(position - 1, convertView, parent);
        }

        @OverridepublicintgetViewTypeCount() {
            return _current.getViewTypeCount();
        }

        @OverridepublicbooleanhasStableIds() {
            return _current.hasStableIds();
        }

        @OverridepublicbooleanisEmpty() {
            return _current.isEmpty();
        }

        @OverridepublicvoidregisterDataSetObserver(DataSetObserver observer) {
            _current.registerDataSetObserver(observer);
        }

        @OverridepublicvoidunregisterDataSetObserver(DataSetObserver observer) {
            // TODO Auto-generated method stub
            _current.unregisterDataSetObserver(observer);
        }

        @Overridepublic View getDropDownView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stubif (position == 0 || position == -1) {
                CheckedTextViewv= (CheckedTextView) ((LayoutInflater) getContext().getSystemService(
                        Context.LAYOUT_INFLATER_SERVICE)).inflate(android.R.layout.simple_spinner_dropdown_item, parent,
                        false);
                v.setText(defaultValue);
                return v;
            }
            return _current.getDropDownView(position - 1, convertView, parent);
        }
    }

Then you can create your own spinner using this decorater :

publicclassSpinnerWithNoValueextendsSpinner {

        publicSpinnerWithNoValue(Context context) {
            super(context);
        }

        publicSpinnerWithNoValue(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        publicSpinnerWithNoValue(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }

        @OverridepublicvoidsetAdapter(SpinnerAdapter orig) {
            finalSpinnerAdapteradapter=newSpinnerAdapterWithNoValue(orig);
            super.setAdapter(adapter);

            try {
                finalMethodm= AdapterView.class.getDeclaredMethod("setNextSelectedPositionInt", int.class);
                m.setAccessible(true);
                m.invoke(this, -1);

                finalMethodn= AdapterView.class.getDeclaredMethod("setSelectedPositionInt", int.class);
                n.setAccessible(true);
                n.invoke(this, -1);

            } catch (Exception e) {
                thrownewRuntimeException(e);
            }
        }

        /*
         * getSelectedItem renvoi null si la valeur par defaut est séléctionnée
         * 
         * @see android.widget.AdapterView#getSelectedItem()
         */@Overridepublic Object getSelectedItem() {
            returnsuper.getSelectedItem();
        }
    }

You just have to change the spinner declaration in your xml layout :



com.myproject.SpinnerWithNoValue

If you want, you can change the code to set the default text in the tag of your spinner.

Solution 3:

The Spinner will always have a selection. What you can do is make the Spinner display something like "Select"or "Select a option"...

To do this you can make your list options to be

actionList = {"Select", "Desactivate" }

and

publicvoidonItemSelected(AdapterView<?> arg0, View arg1, int position, long id){               
        actionList[0] = "Activate";
        ...
 }

or you can do something more complicated like overrides the Spinner View or put a button instead with nothing on it and when it's clicked you create your spinner.

Solution 4:

Try setting this in xml with the prompt attribute:

android:prompt="@string/prompt"

This will also fill in the top of the spinner dialog.

I overlooked this in the documentation. The prompt can not be directly applied. The prompt attribute has to be referenced from another source. Try referencing a string value.

Documentation from Android:

android:prompt

Since: API Level
 The prompt to display when the spinner's dialog is shown.
 Must be a reference to another resource, in the form "@[+][package:]type:name"orto a       theme attribute in the form "?[package:][type:]name".
This corresponds to the global attribute resource symbol prompt.

Solution 5:

I'm just a begginner at android app development, and was facing a similar problem; was able to sort it out using a simple solution- this worked for me, hope it does for you also:

public class AdmissionActivity extends Activity implements OnItemSelectedListener{

int i;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    i=0;
            .........

           }

........ .....

publicvoidonItemSelected(AdapterView<?> parent, View view, 
        int pos, long id){

    if(i!=0){
        //do wat you want;
    }
    else i=1;
            }
            //initially the activity will be loaded and nothing  will happen (since// i=0); and then appropriate action will be taken since i would hav been

// changed to sumtng else

Post a Comment for "Android Spinner - How To Default List Selection To None"