Search code examples
androidandroid-spinnerdefault-valuedropdown

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


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);     
   }
 }

Solution

  • 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();