Selection Controls 2 The spinner Control

The spinner controls is similar to the ComboBox in C#. it displays a list to select from in a popup window so ot may become a better choice over ListView if you want to save space.

It works in a similar way to that of the the listView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android_orientation="vertical"
android_layout_width="fill_parent"
android_layout_height="fill_parent"
>
<Spinner
android_layout_width="fill_parent"
android_layout_height="wrap_content"
android_id="@+id/Spinner"
/>
</LinearLayout>




when you click on the spinner it popups like this:
To handle the selected item you can use do it like this:
final String [] items=new String[]{"Item1","Item2","Item3","Item4"};
ArrayAdapter ad=new ArrayAdapter(this,android.R.layout.simple_spinner_item,items);
ad.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spin=(Spinner)findViewById(R.id.Spinner);
spin.setAdapter(ad);
spin.setOnItemSelectedListener(new OnItemSelectedListener()
{

public void onItemSelected(AdapterView arg0, View arg1,
int arg2, long arg3) {
TextView txt=(TextView)findViewById(R.id.txt);
TextView temp=(TextView)arg1;
txt.setText(temp.getText());

}

public void onNothingSelected(AdapterView arg0) {
// TODO Auto-generated method stub

}

});

The above code displays the selected item text in the textview.

The parameters of the OnItemClick method are:


Arg0:the Spinner, notice that it is of type AdapterView.

Arg1: the view that represents the selected item, in this example it will be a TextView

Arg2: the position of the selected item.

Arg3: the id of the selected item.

and thats it for the Spinner Control.

Related Posts by Categories

0 comments:

Post a Comment

Blog Archive

Powered by Blogger.