askIT

Android Populate spinner from xml

A spinner is a select list where the user can choose between a list of pre defined items. An example is country or month.

populate_spinner_from_xml_first_month.png populate_spinner_from_xml_s_month.png


res\values\strings.xml

We define arrays of months in our strings file. This is done by a string array.

<resources>
    <string name="app_name">My Application</string>

    <string-array name="array_months">
        <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>October</item>
        <item>November</item>
        <item>December</item>
    </string-array>
</resources>

res\layout\activity_main.xml

We create a spinner in our design. We give it the ID spinnerMonth. We assign the entries for the spinner to be the array array_months.

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fitsSystemWindows="true">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginRight="24dp"
        android:layout_marginLeft="24dp">
	
	<Spinner
		android:id="@+id/spinnerMonth"
                android:entries="@array/array_months"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

    </LinearLayout>

</ScrollView>

Add comment

avatar_blank_60.png

Comment:

Name:

Email:

Comments

No comments yet. You can be the first one to comment. Just write your comment in the form and click on the submit button.