List To Spinner

Description:
This example will show how to create spinner with list view in android.
Algorithm:

  1. Create a new project by File-> New -> Android Project name it ListToSpinner.
  2. Write following into main.xml:

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="ListToSpinner" />
<Spinner
android:id="@+id/myspinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>

 

 

  1. Run for output.

Steps:

  1. Create a project named ListToSpinner and set the information as stated in the image.

Build Target: Android 4.2
Application Name: ListToSpinner
Package Name: com.example.ListToSpinner
Activity Name: ListToSpinnerActivity

  1. Open ListToSpinnerActivity.java file and write following code there:

 

package com.example.listtospinner;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class ListToSpinnerActivity extends Activity {

Spinner MySpinner;
List<String> myList;
private ArrayAdapter<String> myAdapter;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MySpinner = (Spinner)findViewById(R.id.myspinner);

initList();
myAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, myList);
myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
MySpinner.setAdapter(myAdapter);
}

void initList(){
myList = new ArrayList<String>();
myList.add("January");
myList.add("February");
myList.add("March");
myList.add("April");
myList.add("May");
myList.add("June");
myList.add("July");
myList.add("August");
myList.add("September");
myList.add("Octomber");
myList.add("November");
myList.add("December");
}
}

 

 

  1. Compile and build the project.

Leave a Comment: