Spinner with an empty default selection
Asked Answered
M

5

13

I have a Spinner which gets populate using a SimpleCursorAdapter. My cursor has some values, but i need the Spinner to show an empty option by default.

I don't want to use ArrayAdapter<String>, or CursorWrapper in this app, for some reason.

There should be a simpler way to show an empty option in the Spinner by default.

Metaprotein answered 28/1, 2012 at 19:56 Comment(1)
here is link how you might do it (adding a dummy item) youtube.com/watch?v=FcMiw16bouAWaggon
A
5

You can simply hide the unwanted view in the spinner adapter (getDropDownView ) :

In my sample code, defaultposition is the position to hide (like a "Select value" position)

public class SpinnerOptionAdapter extends ArrayAdapter<optionsInfos> {

 ...

   @Override

  public View getDropDownView(int position, View convertView, ViewGroup parent)
  {   // This view starts when we click the spinner.
    View row = convertView;
    if(row == null)
    {
        LayoutInflater inflater = context.getLayoutInflater();
        row = inflater.inflate(R.layout.product_tab_produit_spinner_layout, parent, false);
    }

    ...

    optionsInfos item = data.get(position);


    if( (item != null) && ( position == defaultposition)) {
        row.setVisibility(View.GONE);
    } else {
        row.setVisibility(View.VISIBLE);
    }

   ....

    return row;
}


 ...
}
Alcheringa answered 28/4, 2012 at 9:1 Comment(1)
I understand. But you must have a null ítem, and I haven't it in my db. that's the real problema.Metaprotein
F
2

Spinner's OnItemSelectedListener runs on the compile time as well that fetches the first item to view on the Spinner selected item.

Add a dummy item (String - null " ") on your SimpleCursorAdapter and use spinner.setSelected(int thatSpecificPostionYouJustAdded).

Frothy answered 30/1, 2012 at 5:34 Comment(2)
A ArrayAdapter<String> have an 'add' method, but the SimpleCursorAdapter haven´t it. Could you explain how add a null value with code, without using CursorWrapper?. ThanksMetaprotein
Sorry for being late, may be this will help somehow.Frothy
B
2

A method I sometimes use to add an extra record such as an "empty" option with a SimpleCursorAdapter destined for a Spinner is by using a UNION clause in my cursor query. EMPTY_SPINNER_STRING could be something like: "-- none specified --" or similar. Use an "order by" clause to get your empty record first and therefore the default value in the Spinner. A crude but effective way of getting the required result without changing the underlying table data. In my example I only want certain spinners to have a default empty value (those with a modifier type of "intensity".

public Cursor getLOV(String modifier_type)
//get the list of values (LOVS) for a given modifier
{
    if (mDb == null)
    {
        this.open();
    }
    try {
        MYSQL = "SELECT _ID AS '_id', code, name, type as 'DESC', ordering FROM "+codeTab+" WHERE type = '"+modifier_type+"'" +
                " ORDER BY ordering, LOWER(name)";
        if (modifier_type.equals("intensity")) { //then include a default empty record
            MYSQL = "SELECT _ID AS '_id', code, name as 'NAME', type as 'DESC', ordering FROM "+codeTab+" WHERE type = '"+modifier_type+"'" +
                    " UNION SELECT 9999 AS '_id', '' AS 'code', '"+EMPTY_SPINNER_STRING+"' AS 'NAME', 'intensity' AS 'DESC', 1 AS ordering ORDER BY ordering, name";
        }
        Log.d(TAG, "MYSQL = "+MYSQL);
        return mDb.rawQuery(MYSQL, null);
    }
    catch (SQLiteException exception) {
        Log.e("Database LOV query", exception.getLocalizedMessage());
        return null;
    }
}
Busywork answered 1/3, 2013 at 5:57 Comment(0)
V
0

After setting the adapter. call setSelection (i used with 0) and right after that set the text color to transparent.

    // Preselect the first to make the spinner text transparent
    spinner.setSelection(0, false);
    TextView selectedView = (TextView) spinner.getSelectedView();
    if (selectedView != null) {
        selectedView.setTextColor(getResources().getColor(R.color.transparent));
    }

Then, set your OnItemSelectedListener (if needed).

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

This will make the spinner empty at first time seen. But, if the user will select the first item it will do nothing because 0 is pre selected. For fixing this i used this subclass of spinner. taken from @melquiades's answer:


/** 
  * Spinner extension that calls onItemSelected even when the selection is the same as its previous value
  */
public class FVRSpinner extends Spinner {

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

    public FVRSpinner(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FVRSpinner(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void setSelection(int position, boolean animate) {
        boolean sameSelected = position == getSelectedItemPosition();
        super.setSelection(position, animate);
        if (sameSelected) {
            // Spinner does not call the OnItemSelectedListener if the same item is selected, so do it manually now
            if (getOnItemSelectedListener() != null) {
                getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId());
            }
        }
    }

    @Override
    public void setSelection(int position) {
        boolean sameSelected = position == getSelectedItemPosition();
        super.setSelection(position);
        if (sameSelected) {
            // Spinner does not call the OnItemSelectedListener if the same item is selected, so do it manually now
            if (getOnItemSelectedListener() != null) {
                getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId());
            }
        }
    }
}
Vaginal answered 17/12, 2015 at 12:32 Comment(0)
C
0

Create a NullSpinnerItem class and inject it at the start of the list.

// Class to represent the `null` selection in a List of items in a Spinner.
// There is no easy way to tell Spinner to also include a blank or null value. 
// This allows us to inject this as the first item in the List and handle null values easily.
//
public class NullSpinnerItem {

  @Override
  public String toString() {
    return "None";
  }

}

Then when you're populating your spinner, just get your items and then add it to the first position:

items.add( 0, new NullSpinnerItem() ); // items are your items.

ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource( R.layout.spinner_list_item);

Spinner spinner = (Spinner) findViewById(spinnerId);
spinner.setAdapter(adapter);

The toString() method is what is displayed in the Spinner.

Conk answered 28/5, 2019 at 2:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.