Android Example To Create Spinner

      No Comments on Android Example To Create Spinner
activity_main.xml

Drag the spinner from the pallete

<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" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="34dp" />

</RelativeLayout>

Activity Class

Write the code in activity class

File name:- MainActivity.java
package com.example.scanfcode;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.*;
import android.widget.AdapterView.OnItemSelectedListener;

public class MainActivity extends Activity implements OnItemSelectedListener
{
  Spinner s1;
  
  String[] city={"Mumbai","Banglore","Delhi","chennai"};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		s1=(Spinner)findViewById(R.id.spinner1);
		
		s1.setOnItemSelectedListener(this);
		
	  ArrayAdapter a1=new ArrayAdapter(this,android.R.layout.simple_spinner_item,city);
	  a1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	  
	  s1.setAdapter(a1);
	  
	}
@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) 
{
		// TODO Auto-generated method stub
       String s=city[arg2];
       Toast.makeText(getApplicationContext(),s,Toast.LENGTH_SHORT).show();
	}

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

}

OUTPUT

scanfcode
scanfcode

Leave a Reply

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