How do you rate this blog

Friday, November 25, 2011

Spinner


A spinner is just like a drop down list with combo box which displays multiple items out of which a user can select one item.

In this post I have created an app which demonstrates the spinner. In order to do this, I have an array which has the list of values which need to be present in the list. On clicking one of the items I will display an alert dialog which will confirm the selection of the item.
So, first we will modify the layout. Open the ‘main.xml’ file in Layouts and remove the existing text box and add a new Large Text and add the app name to it. Then drag and drop the spinner item from the list into the layout and make its width the same as the parent’s width. The layout will finally look like the one shown below.



After this open the main java file in src folder within the package. As you can see it will just extend Activity by default but since we are using adapter we also need onItemSelectedListner.  Then it you need to implement methods like ‘ontemSelected’ and ‘onNothingSelected’ .Then we need to declare an array of string with the items of your choice or requirement.  Then create a spinner and arrayadapter which will hold the items as shown below.
Spinner spinner=(Spinner) findViewById(R.id.spinner1);
 spinner.setOnItemSelectedListener(this);
ArrayAdapter spinadapter=new ArrayAdapter(this,android.R.layout.simple_spinner_item,spinneritems);
spinadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinadapter);

Now you need to define action if the item is selected. So go to the function onItemSelected and get the item name into a string and then create an alert dialog with Done button which will display the item which has been selected by you.  The code for the same is provided below.
String items=(String) adapter.getAdapter().getItem(pos);
AlertDialog.Builder spinalert=new AlertDialog.Builder(SpinnerDemoActivity.this);
spinalert.setTitle("Spinner Demo - Alert");
spinalert.setMessage("You clicked on :"+items);
spinalert.setPositiveButton("Done", null);
spinalert.show();

Do the same for onNothingSelected where you just create an alert dialog with some default message.
The java file will look like in the image shown below.
 


Now right click on the project and say run as android application, the first output screen that you get is as shown below.



No click on the dropdown and you get a list of combo boxes as shown below.



Click on anyone of them and you get an alert dialog which will display the item which you have selected.


No comments:

Post a Comment