Change color of the Spinner Android - Androchunk


In the previous post, you learn how to create simple spinner in android in two different ways,
  1. With adapter.
  2. Without adapter using android: entries attribute.
Now from this post, you'll learn how to change the color of the selected item and dropdown items of the spinner in android.


colored_spinner



To change the color of spinner you'll need two different layouts,
  1.  CheckedTextView: use for the selected item of the spinner.
  2.  TextView:- use for the item of the dropdown list.


Follow these steps to change the color of the spinner.
  1. Create a Spinner element in your XML layout.
  2. Create a list for the spinner.
  3. Create a layout for the selected item of the spinner.
  4. Create a layout for the item of the dropdown list.
  5. Create the spinner adapter using the Spinner Adapter class and set the CheckedTextView layout as a spinner layout and TextView for the item of the dropdown list.
  6.  Attach the adapter to Spinner and setOnItemSelectedListener to Spinner.

Create a Spinner element in your XML layout: write the following code in your XML file.

Create ArrayList for the spinner: you’ll need data to display into the spinner as a dropdown list so for that you’ll need to create ArrayList for the spinner. The following shows a simple array called spinner_items. Copy the following values in the strings.xml file:


Create a layout for the selected item of the spinner: create new layout file name color_spinner_layout.xml with CheckedTextView as a root element. Copy the following values in the color_spinner_layout.xml file:


Create a layout for the item of the dropdown list: create new layout file name spinner_dropdown_layout.xml with TextView as a root element. Copy the following values in the spinner_dropdown_layout.xml file.



Create the spinner adapter: Adapter is used as a bridge in the spinner. It attaches list data into the spinner and creates a dropdown list of that data.do this is when the view is created in the onCreate() method.

 adapter from the resource(ArrayList ) take 3 parameters,
  1. context.
  2.  list: here your list from the string.xml
  3. layout for the spinner selected item: your custom layout for spinner selected item.
set spinner_dropdown_layout as a DropDownViewResource for custom drop down items.



Attach the adapter to Spinner and setOnItemSelectedListener to Spinner:


For handle the item selection you’ll need to attach onItemSelectedListener to the spinner and implement it’s two methods.
  1.  onItemSelected: this method called when item selection is changed.
  2.  onNothingSelected: this method call when no item is selected for ex: remove the selected item from the list


If you have any questions or suggestions  please leave them in the comments.

Full Source Code : https://github.com/Androchunk/ColoredSpinner


Question of the Day

Create custom spinner like this,

Solution :


Official documentation:






Post a Comment

0 Comments