Tuesday, July 5, 2011

Android Spinner Default Value

we are going to see how to set a default value to spinner in android?

In Android, Spinner is nothing but a combo box or list box.
It lets you viewing multiple items and allows you to select one item from the list.
Edit Your XML code like this
Now, we can set a default value to Spinner by using setSelection in Spinner.
[sourcecode language="css"]
Edit the below Java code
<Spinner android:id="@+id/Spinner01"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
[/sourcecode]


[sourcecode language="java"]
public class SpinnerExample extends Activity {
private String array_spinner[];
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
array_spinner=new String[5];
array_spinner[0]="1";
array_spinner[1]="2";
array_spinner[2]="3";
array_spinner[3]="4";
array_spinner[4]="5";
Spinner s = (Spinner) findViewById(R.id.Spinner01);
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, array_spinner);
s.setAdapter(adapter);
s.setSelection(2);
}
}
[/sourcecode]
Here I choose the 2nd value. So the corresponding output value is 3.
The output will look like
spinnerdefaultvalue

5 comments:

  1. thank you very much.

    ReplyDelete
  2. thank you

    premkumar mani

    ReplyDelete
  3. Many thanks. I was looking for this for quite some time.

    ReplyDelete