Wednesday, May 2, 2012

Creating Spinner


Creating Spinner



The project describes how to implement spinner (drop-down list) for your application.
Underlying Algorithm:
Basic description of algorithm in step by step form:
1.) Create a Project SpinnerExample
2.) Open and insert following in main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:padding="10dip"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content">
    <TextView
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:layout_marginTop="10dip"
       android:text="@string/mnth_picker"
   />
    <Spinner 
       android:id="@+id/spinner"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:prompt="@string/mnth_picker"
   />
</LinearLayout>
3.) Open and insert following in strings.xml:
<resources>
    <string name="hello">Hello World, SpinnerExample!</string>
    <string name="app_name">SpinnerExample</string>
    <string name="mnth_picker">Select a Month</string>
    <string-array name="mnth_array">
        <item>January</item>
        <item>February</item>
        <item>March</item>
        <item>April</item>
        <item>May</item>
        <item>June</item>
        <item>July</item>
        <item>August</item>
        <item>September</item>
        <item>Octomber</item>
        <item>November</item>
        <item>December</item>
    </string-array>
</resources>
4.) Run the application.
Steps to Create:
1.) Open Eclipse. Use the New Project Wizard and select Android Project Give the respective project name i.e. SpinnerExample. Enter following information:
Project name: SpinnerExample
Build Target: Android 2.3.3
Application name: SpinnerExample
Package name: org.example.SpinnerExample
Create Activity: SpinnerExample
On Clicking Finish SpinnerExample code structure is generated with the necessary Android Packages being imported along with SpinnerExample.java. SpinnerExample class will look like following:
package org.example.SpinnerExample;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class SpinnerExample extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Spinner spinner = (Spinner) findViewById(R.id.spinner);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.mnth_array, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
    }
}
Output – The final output:
Share and Enjoy

No comments: