0

By all means this is a very basic question what i am about to ask. I have a spinner which i am populating using an array list and its working fine but i want to add a constant string at the first position of my spinner for instance "Select service" should be my first elemnent how can i do this.Any help is appreciated.Thank you.

ArrayAdapter<String> adapter =new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_item,ar1);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spin_dept.setAdapter(adapter);

             spin_dept.setOnItemSelectedListener(new OnItemSelectedListener() 
                {

                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) 
                    {
                        ((TextView) parent.getChildAt(0)).setTextColor(Color.RED);
                        ((TextView) parent.getChildAt(0)).setTextSize(13);
                        name = spin_dept.getSelectedItem().toString();
                        Log.d("NAME",name);
                        Id = spinnerMap.get(name);
                         Log.d("ID",Id);
                         new LongOperation1().execute();


                    }

above is the code where I am populating the spinner

darshan kodkany
  • 51
  • 1
  • 1
  • 8

2 Answers2

0

If you are setting the spinner values by arraylist or array you can set the spinner's selection by using the index of the value.

String myString = "Select service"; //the value you want the position for

ArrayAdapter myAdap = (ArrayAdapter) mySpinner.getAdapter(); //cast to an ArrayAdapter

int spinnerPosition = myAdap.getPosition(myString);

//set the default according to value
spinner.setSelection(spinnerPosition);

if you are populating with array ar1 then

ar1[0]="Select service";
spinner.setSelection(0);
Subin Chalil
  • 3,531
  • 2
  • 24
  • 38
0

ArrayList ar1=new ArrayList<>(); ar1.add(0,"Select service","service 1","service 2","service 3");

use this above your given code

Akash kv
  • 429
  • 4
  • 13