How to Implement Dependent Dropdown in Android?
The concept of dependent dropdown uses two spinners where the value of one spinner depends on the other spinner. Dropdown is implemented using spinners, spinners provide a quick way to select one value from a set. In the default state, a spinner shows its currently selected value. Touching the spinner displays a dropdown menu with all other available values, from which the user can select a new one. In this article, we will learn that how we can implement dependent dropdown in android studio.
What we are going to build in this article?
In this article, we will be using two dropdown menus where the value of the second menu will be directly dependent on the first one i.e. if the value of the first menu will increase then the value of the second menu will also increase and if we will decrease the value of the first menu then the value of the second menu will also decrease by same difference. Here is a sample video of the application which we are going to build. Note that we are going to implement this project in Java Language.
Step by Step Implementation
Step 1: Create a new project
- Open a new project.
- We will be working on Empty Activity with language as Java. Leave all other options unchanged.
- You can change the name of the project at your convenience.
- There will be two default files named activity_main.xml and MainActivity.java.
If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio?
Step 2: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
Step 3: Working with item_dropdown.xml file
Follow the path app > res > layout > right click > new > layout resource file and create a new file named as item_main.xml. Use the below code in item_dropdwon.xml file-
Step 4: Working with MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Here is the final output of our application.