Android Spinner – UI Widget

spinner_tutorial

Spinner is a Android Widget which is used to select one value among lot of values given in array.It is very simple to work with. lets code –

Download Code

First of all you have to take spinner widget in 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"
    tools:context=".MainActivity" >

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="83dp" />

</RelativeLayout>

Now in MainActivity.java you have to define a String type Array and adapter and set adapter to spinner .

Make sure your MainActivity.java file should implement AdapterView.OnItemSelectedListener . I take version Array of String type and Adapter aa .

MainActivity.java

package androidarena.spinner;
import androidarena.spinner.R;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements
AdapterView.OnItemSelectedListener {

	String[] version = { "donut", "cupcake", "kitkat", "jelly bean", "Other",  };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		Spinner spin = (Spinner) findViewById(R.id.spinner1);
		spin.setOnItemSelectedListener(this);
		
		ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,version);
		aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		
		spin.setAdapter(aa);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int position,long id) {
		Toast.makeText(getApplicationContext(),version[position] ,Toast.LENGTH_LONG).show();
	}

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

}

Output –

spinner output spinner_output

For more queries and tutorials do post here and comment . Happy coding :p

Leave a Reply

Your email address will not be published. Required fields are marked *