askIT

Android Populate spinner from Java

You can fill in the items in a spinner select list by a array in your Java code. First define a spinner in your design.

res\layout\activity_main.xml

Here we create a spinner with the ID spinnerDay.

<?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/spinnerDay"
                android:entries="@array/array_months"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

    </LinearLayout>

</ScrollView>

java\your.com.package\MainActivity.class

package com.package.your;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Spinner;


public class MainActivity extends AppCompatActivity {


        /* Variables */
        private String[] arraySpinnerDay = new String[31];


        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);


                /* Fill numbers for date of birth days */
                int human_counter = 0;
                for(int x=0;x<31;x++){
                        human_counter=x+1;
                        this.arraySpinnerDay[x] = "" + human_counter;
                }

                Spinner spinnerDay = (Spinner) findViewById(R.id.spinnerDay);
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                                android.R.layout.simple_spinner_item, arraySpinnerDay);
                spinnerDOBDay.setAdapter(adapter);


        }

}

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.