Android Spinner
Spinner allows you to select an item from a drop down menu.
For example. When you are using Gmail application you would get drop down menu as shown below, you need to select an item from a drop down menu.
Example
This example demonstrates the category of computer courses, you need to select a category from the category.
Steps :
- Define all courses in
res/values/strings.xml
<string-array name = "course_items">
<item>C</item>
<item>C++</item>
<item>Java</item>
<item>.Net</item>
<item>MySql</item>
</string-array>
- Add Spinner in
res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Spinner
android:id="@+id/sp_courses"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="@array/course_items"
/>
<Button
android:id="@+id/btn_submit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Submit" />
</LinearLayout>
android:entries represents the selection items in spinner.
- Add code in
src/your app package/MainActivity.java
package com.example.androidcollegeppt;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
public class Spinner_Demo extends Activity {
Spinner sp_courses;
Button btn_submit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.a_spinner_demo);
sp_courses = (Spinner) findViewById(R.id.sp_courses);
btn_submit = (Button) findViewById(R.id.btn_submit);
btn_submit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getBaseContext(), sp_courses.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
}
});
}
}
OUT PUT