WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

Spinner Tutorial Android


Spinner helps to select one value from a set of values.In android default mode a spinner shows its currently selected value.


XML example of spinner
<Spinner
android:id="@+id/demoSpinner "
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
ArraryAdapter ArraryAdapter is used to bridge between user interface component and data source that helps us to fill data in user interface component.
ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects)

Example of android spinner

open android studio name it demoExample.
Select File -> New -> New Project ->. Fill the forms and click "Finish" button.

Open res -> layout -> activity_main.xml (or) main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<Spinner
android:id="@+id/simpleSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="200dp" />

</RelativeLayout>

open app-> java -> package -> MainActivity.java
package example.welookups.spinnerexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{

String[] FlowerNames ={"African Daisy","Alstroemeria","Anemone","Aquilegia","Astrantia"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Getting the instance of Spinner and applying OnItemSelectedListener on it
Spinner spin = (Spinner) findViewById(R.id.demoSpinner);
spin.setOnItemSelectedListener(this);

//Creating the ArrayAdapter instance having the bank name list
ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,FlowerNames);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spin.setAdapter(aa);
}


//Performing action onItemSelected and onNothing selected
@Override
public void onItemSelected(AdapterView arg0, View arg1, int position,long id) {
Toast.makeText(getApplicationContext(), bankNames[position], Toast.LENGTH_LONG).show();
}

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

}
}

Custom Spinner

It is used to display a spinner item with image, text etc