How to set my first value (default value) in spinner as empty
Asked Answered
F

5

1

How to set my first value (default value) in spinner as empty. Means, until the user selects value from list, spinner will have no value. I tried below

list.add(""); 

But, it won't work. Below is my code :

if(values.contains("options")){
       spinner.setOnItemSelectedListener(MyClass.this);
       List<String> list = new ArrayList<String>();
       list.add("");
       list.add("Test");
       list.add("Working");
       ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_item, list) {};

      adapter.setDropDownViewResource(R.layout.custom_spinner_list);
      spinner.setAdapter(adapter);     
   }
 }
Flub answered 15/9, 2015 at 11:45 Comment(7)
empty means what you want to setOrganism
@user3676184 - Empty means "null" value or "nothing" stringFlub
No Rustam, I don't want to clear my list, i just want the default value of spinner to be empty, means value will only be shown once user selects, until then spinner will have no valueFlub
Have you tried spinner.setPrompt(""); or put this in your xml (Spinner) android:prompt=""Carboni
what is showing currently by default to the spinner ?Opine
@HradeshKumar - ofcourse, it will show the first value from array listFlub
@Skizo - Thanks but setPrompt only works when you have static spinner with string items defined in resourceFlub
F
10

i found out the way. Here is how we do it, let the last line be

list.add("");

and add below code :

ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_item, list) {

                        @Override
                        public View getView(int position, View convertView, ViewGroup parent) {

                                View v = super.getView(position, convertView, parent);
                                if (position == getCount()) {
                                    ((TextView)v.findViewById(android.R.id.text1)).setText("");
                                    ((TextView)v.findViewById(android.R.id.text1)).setHint(getItem(getCount())); //"Hint to be displayed"
                                }

                                return v;
                            }       

                            @Override
                            public int getCount() {
                                return super.getCount()-1;            // you don't display last item. It is used as hint.
                            }

                    };


                    adapter.setDropDownViewResource(R.layout.custom_spinner_list);
                    spinner.setAdapter(adapter);
                    spinner.setSelection(adapter.getCount());        //set the hint the default selection so it appears on launch.
                    spinner.setOnItemSelectedListener(this);
                    notifyDataSetChanged();        
Flub answered 15/9, 2015 at 12:21 Comment(1)
This is a terrific solution, as it avoids having to hack the first view from not appearing. I posted a SpinnerNoDefault class below which takes this answer into account. Thanks!Lorelle
L
1

Thanks to user45678's answer above, I wrote this

public class SpinnerNoDefault extends Spinner {

public void initialize(List<String> items) {
    initialize(items, android.R.layout.simple_spinner_item, android.R.layout.simple_spinner_dropdown_item);
}

public void initialize(List<String> items, @LayoutRes int mItemResId, @LayoutRes int dropdownResId) {
    List<String> itemsWithEmpty = new ArrayList<>(items);
    itemsWithEmpty.add("");

    String[] choicesArray = itemsWithEmpty.toArray(new String[itemsWithEmpty.size()]);
    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(getContext(), mItemResId, choicesArray) {
        @NonNull
        @Override
        public View getView(int position, View convertView, @NonNull ViewGroup parent) {
            View v = super.getView(position, convertView, parent);
            if (position == getCount()) {
                ((TextView)v.findViewById(android.R.id.text1)).setText(null);
                ((TextView)v.findViewById(android.R.id.text1)).setHint(parent.getContext().getString(R.string.spinner_no_default_hint));
            }

            return v;
        }

        @Override
        public int getCount() {
            // Don't display last item. It is used as hint.
            return super.getCount()-1;
        }
    };

    spinnerArrayAdapter.setDropDownViewResource(dropdownResId);
    setAdapter(spinnerArrayAdapter);
    setSelection(itemsWithEmpty.size()-1);
}
}
Lorelle answered 7/10, 2016 at 17:56 Comment(0)
P
1
    List<String> allGoverNames = new ArrayList<String>();
    allGoverNames.add(0, "");
    allGoverNames.add(1,"Cricket");
    allGoverNames.add(2,"FootBall");
    allGoverNames.add(3,"Chess");


ArrayAdapter<String> GoverdataAdapter = new ArrayAdapter<String>
                            (context, android.R.layout.simple_spinner_item, allGoverNames);

                    GoverdataAdapter.setDropDownViewResource
                            (android.R.layout.simple_spinner_dropdown_item);

                    GovernorateSpinner.setAdapter(GoverdataAdapter);
Postmistress answered 13/8, 2019 at 12:46 Comment(0)
H
1

In SearchableSpinner (com.toptoche.searchablespinnerlibrary.SearchableSpinner) there is a parameter called "app:hintText" - you can use it for your purpose. For example:

<com.toptoche.searchablespinnerlibrary.SearchableSpinner
            android:id="@+id/vehicle_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/spinner_background"
            android:layout_marginStart="20dp"
            android:layout_marginEnd="20dp"
            android:layout_marginBottom="20dp"
            app:hintText=" "/>

Hint will dissapear once something will be chosen from the Spinner list.

Hygroscopic answered 20/10, 2020 at 12:57 Comment(0)
O
0

At first. When you initialize your spinner add

spinner.setSelection(0, false)

And I created this adapter with selected item:

abstract  class SpinnerSelectAdapter<T>(
    context: Context,
    private val resource: Int,
    @ColorRes private  val unselectedColorResource: Int,
    @ColorRes private val selectedColorResource: Int,
    open var objects: List<T>
) :
    ArrayAdapter<T>(context, resource, objects) {

    var selectedPosition = -1

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val view = convertView ?: LayoutInflater.from(parent.context)
            .inflate(resource, parent, false)
        if(selectedPosition != -1) {
            setView(view, getItem(position)!!)
        }
        return view
    }

    override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
        val view = convertView ?: LayoutInflater.from(parent.context)
            .inflate(resource, parent, false)
        if(selectedPosition == position){
            view.setBackgroundResource(selectedColorResource)
        }else {
            view.setBackgroundResource(unselectedColorResource)
        }
        setView(view, getItem(position)!!)
        return view
    }

    open fun setView(view: View, item: T) {

    }

    open fun setEmptyView(view: View){

    }


    override fun getItem(position: Int): T? {
        return objects[position]
    }


    override fun getCount(): Int {
        return objects.size
    }
}

Then I created adapter for String Values inherited from SpinnerSelectAdapter

class SpinnerStringAdapter(
    context: Context,
    resource: Int,
    @ColorRes unselectedColorResource: Int,
    @ColorRes selectedColorResource: Int,
    override var objects: List<String>
) :
    SpinnerSelectAdapter<String>(
        context,
        resource,
        unselectedColorResource,
        selectedColorResource,
        objects
    ) {


    override fun setView(view: View, item: String) {
        val txt = view.findViewById<TextView>(android.R.id.text1)
        txt.text = item
    }

}

And after in your fragment or activity

       val adapter = SpinnerStringAdapter(
           requireContext(),
           R.layout.spinner_item,
           R.color.colorBG,
           R.color.colorSubBG,
           types
       )
       spinner.adapter = typeAdapter
       spinner.setSelection(0, false)
       spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
           override fun onItemSelected(
               parent: AdapterView<*>?,
               view: View?,
               position: Int,
               id: Long
           ) {
               adapter.selectedPosition = position
               adapter.notifyDataSetChanged()
           }
``
Orchitis answered 8/12, 2020 at 9:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.