Android

【Android Studio】How to Customize Spinner

 

In this post, I’m going to share how to customize Spinner.

We’re going to customize:

  • Background color
  • Text color
  • Text alignment

 

 
 


 

Environment

Android Studio 3.4
Android Emulator Nexus 5 (API 27)

In this example, I assume that you have activity_main.xml and MainActivity.java in your project.

 
 

Video

【Android Studio】How to Customize Spinner

 
 

Customize

Step1: Prepare an array to display in Spinner

Open res → values → strings.xml.


 

Add lines 4-8.

 
 

Step2: Set Spinner in activity_main.xml

Open activity_main.xml and set Spinner.

 


 

Line 13

android:entries="@array/list"

Set the list array which we created in Step 1.
 

Line 15

android:background="@android:color/holo_blue_light"

Change the background color.

You can set color directly like "#33B5E5" or define in res → values → colors.xml file.

 
 

Step3: Create custom_spinner.xml

Right click on layout folder and select New → Layout resource file.


 
 

Enter custom_spinner in File name, then click “OK” button.

 
 

Write code in custom_spinner.xml

 
 


 

Line 9

android:textColor="@android:color/white"

Set text color.
 

Line 10

android:background="@drawable/abc_spinner_mtrl_am_alpha"

Set a down-arrow image in the background.
 

Line 11

android:backgroundTint="@android:color/white"

Set the color of the down-arrow image.

 
 

Step4: Create custom_spinner_dropdown.xml

Create custom_spinner_dropdown.xml in the same way as custom_spinner.xml


 
 

Write code in custom_spinner_dropdown.xml

 
 

 

Lines 9-10

Set textColor and backgroundColor.
 

Line 11

android:textAlignment="center"

Align text in the center.

If you want to align text not only in Dialog but in Spinner, add textAlignment to Spinner tag in activity_main.xml.

 
 

Step5: Reflect customized XML files in Spinner

Open MainActivity.java and add lines 5, 6, 15-23.

 
 

Step6: Get selected item

Finally, let’s get an selected item name.

Add lines 15-25 in MainActivity.java.

 
 

Done!

 
 

 

ABOUT ME
Sara
Working as a freelance programmer in Japan. I try to make coding as simple as possible. Hope you enjoy coding 🙂