Android tutorial : Spinner basics


The Spinner of Android is the equivalent of drop-down boxes that are found in some development kits (JComboBox in Java / Swing, for example). Press  central button of the terminal pad brings out a dropdownlist allowing the user making his choice. We can choose from a list without occupying the entire screen as with a ListView, but at the cost of an extra click.
As ListView, we must provide the adapter for data and child views via setAdapter () and a listener is hung with setOnItemSelectedListener ().
If you want to customize the display of the combo box, you must configure  the adapter, not the Spinner widget. To do this, we need a method therefore  setDropDownViewResource () for providing the identifier of the relevant picture.
Here is a sample xml code to implement a simple view containing a Spinner:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_height="fill_parent" 
    android:layout_width="fill_parent" 
    android:orientation="vertical" 
   >
<TextView android:id="@+id/selection" 
    android:layout_height="wrap_content" 
    android:layout_width="fill_parent"/>
<Spinner 
   
    android:id="@+id/spinner"
     android:layout_height="wrap_content" 
     android:layout_width="fill_parent">
</Spinner>
</LinearLayout>

 Here is the Java code to populate and use the Spinner:
public class SpinnerActivity extends Activity implements AdapterView.OnItemSelectedListener {
TextView selection;
String[] items={"Tunisia", "Algeria", "Egypt", "France", "Germany",
"Tchad", "USA", "Cananda", "Belgium", "KSA",
"UAE", "China", "Malta", "Spain", "UK",
"Russia", "South Africa", "Danemark", "Finland", "Argentina",
"Poland", "Turkey", "Oman", "Italy", "Singapur"};
@Override
public void onCreate(Bundle bnd) {
super.onCreate(bnd);
setContentView(R.layout.main);
selection=(TextView)findViewById(R.id.selection);
Spinner spin=(Spinner)findViewById(R.id.spinner);
spin.setOnItemSelectedListener(this);
ArrayAdapter ang=new ArrayAdapter(this,
android.R.layout.simple_spinner_item,
items);
 ang.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(ang);
}
public void onItemSelected(AdapterView parent,
View v, int position, long id) {
selection.setText(items[position]);
}
public void onNothingSelected(AdapterView parent) {
selection.setText("");
}
}

Commentaires

Posts les plus consultés de ce blog

Ionic 2 : Envoie d'une image vers un serveur web à l'aide de PHP et Angular 2

Premier tutoriel avec Arduino et Proteus ISIS

Login et password ,formulaire d'authentification sous android avec mysql et json