Populate and Select a Spinner Item once another Spinner Item is Selected

In my android tips section, I usually write about common issues beginners android developers face and the solution to it. Today we will learn how to populate and select a spinner item once another spinner item is selected.

This can come in handy when you have corresponding or matching values you need in your application. Imagine if you want to select a country from a spinner and you will like once you select a country, its corresponding country code will appear in another spinner. This will save a user some time that would have been spent searching for the code.

Before we dive into more details, it is important for us to understand what we are planning to achieve. Below is the screen-shot of the application we will be creating.

android spinners

Lets start to soil our hands in code. Start up your IDE. For this tutorial, I am using the following tools and environment, feel free to use what works for you.

Windows 7

Android Studio

Sony Xperia ZL

Min SDK 14

Target SDK 23

To create a new android application project, follow the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidSpinnerToSpinner

Package: com.inducesmile.androidspinnertospinner

Select Blank Activity

Name your activity : MainActivity

Keep other default selections

Continue to click on next button until Finish button is active, then click on Finish Button.

Strings.xml

We are going to update our project strings.xml file located in the values folder inside the res folder. Open the file and add the code below to it.

<string name="app_name">Spinner Enable Another Spinner</string>
<resources>
    <string name="app_name">Spinner Enable Another Spinner</string>
    <string name="select_country">Select a country and see the country code in another spinner</string>
    <string-array name="first_spinner">
        <item>Afghanistan</item>
        <item>Albania</item>
        <item>Algeria</item>
        <item>American Samoa</item>
        <item>Andorra</item>
    </string-array>
    <string-array name="second_spinner">
        <item>AF</item>
        <item>AX</item>
        <item>AL</item>
        <item>Dz</item>
        <item>AS</item>
    </string-array>
</resources>

Colors.xml

Open the colors.xml file in the same location as the strings.xml file and add the code below to the file.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="colorBlack">#000000</color>
    <color name="colorDivider">#727272</color>
</resources>

Activity_main.xml

Open the default layout file that Android Studio created for us when we first created our project. Go to res folder – layout folder and double click on activity_main.xml. We are going to add a TextView and two Spinners widgets. Add the below code to the file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.inducesmile.spinnertospinner.MainActivity">
    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/select_country" />
    <Spinner
        android:id="@+id/first_spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:padding="13dp"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/title"
        android:background="@drawable/bottom_border"
        android:textColor="@color/colorBlack" />
    <Spinner
        android:id="@+id/second_spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:padding="13dp"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/first_spinner"
        android:background="@drawable/bottom_border"
        android:textColor="@color/colorBlack" />
</RelativeLayout>

MainActivity.java

Inside our package folder, double click on java folder to open the folder, then open the MainActivity.java file. We will get the instances of the Spinner widgets. Thereafter, we will create an adapter for our spinners.

The adapters will take a string-array declared in the strings.xml file as one of its parameters and data source.

If you are looking for how to populate android spinner object from a local SQLite database, I will suggest you read my tutorial on Populate android spinner from SQLite Database. If you prefer to populate your spinner object with a remote MYSQL database then read this – Populate android spinner data from remote MYSQL database.

Finally, we are going to attach an item click event to the country spinner so that when a new item is selected it will change the item selected in the country code spinner. The countryCodeSpinner object is disable so that a user will not change the current selected country code which corresponds to the country code.

Feel free to modify this code to suit your project require since that are different other ways we can slightly change this functionality.
Open the file and add the below codes to the file.

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class MainActivity extends AppCompatActivity {
    private Spinner countrySpinner;
    private Spinner countryCodesSpinner;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        countrySpinner = (Spinner)findViewById(R.id.first_spinner);
        countryCodesSpinner = (Spinner)findViewById(R.id.second_spinner);
        countryCodesSpinner.setEnabled(false);
        ArrayAdapter<CharSequence> countryAdapter = ArrayAdapter.createFromResource(this, R.array.first_spinner, android.R.layout.simple_spinner_item);
        countryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        ArrayAdapter<CharSequence> countryCodesAdapter = ArrayAdapter.createFromResource(this, R.array.second_spinner, android.R.layout.simple_spinner_item);
        countryCodesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        countrySpinner.setAdapter(countryAdapter);
        countrySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                countryCodesSpinner.setSelection(position);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        countryCodesSpinner.setAdapter(countryCodesAdapter);
    }
}

This brings us to the end of this tutorial. I hope that you have learn something. Run your app to see for yourself.

You can download the code for this tutorial below. If you are having hard time downloading the tutorials, kindly contact me.

Remember to subscribe with your email address so that you will be among the first to receive my new android blog post once it is published.

Please if you love this tutorial, kindly download my android app – Complete Mathematics – in Google Play Store and let me know what you think about it.

OTHER INTERESTING POSTS:

Add a Comment