How to Set Spinner in Android

Spinner

Spinners provide a quick way to select one value from a set. In the default state, a spinner shows its currently selected value.

Procedure

  1. Start the Eclipse IDE.
  2. Create a new project.
  3. Create a MainActivity.java file.
  4. Create an activity_main.xml for layout design.
  5. Declare a spinner in XML layout, for example:

    <Spinner
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/ss"/>

  6. Declare a string array with some elements and pass these elements to the ArrayAdapter.

    For instance:

    String[] str={"select","yellow","red","Green","purple","blue"};
    ArrayAdapter<String> adap=new ArrayAdapter<String>
    (this, android.R.layout.simple_spinner_item,str);

The code is given below.

MainActivity.java

package com.example.spinnertodayy;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
Spinner s1;
RelativeLayout ll;
String[] str={"select","yellow","red","Green","purple","blue"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
s1=(Spinner) findViewById(R.id.ss);
ll=(RelativeLayout) findViewById(R.id.rr);
ArrayAdapter<String> adap=new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_item,str);
s1.setAdapter(adap);
s1.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
String ss1=arg0.getItemAtPosition(arg2).toString();
String ss=((TextView)arg1).getText().toString();
Toast.makeText(getApplicationContext(), ss, 10000).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}



activity_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:id="@+id/rr"
   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:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/ss"/>
</RelativeLayout>

Output



Up Next
    Ebook Download
    View all
    Learn
    View all