In the previous post, you learn how to create simple spinner in android in two different ways,
- With adapter.
- Without adapter using android: entries attribute.
To change the color of spinner you'll need two different layouts,
- CheckedTextView: use for the selected item of the spinner.
- TextView:- use for the item of the dropdown list.
Follow these steps to change the color of the spinner.
- Create a Spinner element in your XML layout.
- Create a list for the spinner.
- Create a layout for the selected item of the spinner.
- Create a layout for the item of the dropdown list.
- 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.
- 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,
- context.
- list: here your list from the string.xml
- layout for the spinner selected item: your custom layout for spinner selected item.
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.
- onItemSelected: this method called when item selection is changed.
- 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
Full Source Code : https://github.com/Androchunk/ColoredSpinner
Question of the Day
Create custom spinner like this,
Solution :
Official documentation:
AdapterView.OnItemSelectedListener:https://developer.android.com/reference/android/widget/AdapterView.OnItemSelectedListener
0 Comments