In this post, you learn how to create a custom spinner in android.
Steps to create a custom Spinner
- Create a Spinner Element in your XML file.
- Create the custom layout for Spinner element.
- Create the Getter/Setter method for Spinner element.
- Create Adapter for the Spinner.
- Create Item List for the spinner.
- Implement OnItemSelectedListener for Spinner.
- Full Source Code & Output.
Create a Spinner element.
Add spinner element in your layout.xml file.write the following code in your activity_main.xml file.Custom Layout for Spinner
create a new layout file name custom_spinner_layout.xml and design spinner layout, here we use ImageView and TextView for Spinner Item.Getter/Setter method for Spinner element
create a class name CustomItems.java and add a getter/setter method for each variable of the custom item.Adapter for the Spinner
Create Adapter class to render data into the spinner. Create class name CustomAdapter.java and extends it to ArrayAdapter<CustomItems>. Override two methods,getView: return view of spinner with selected item position.
getDropDownView: return view of dropdown list of the spinner
here we have same view for both methods so we create new method customView and use it for both methods.
Item List for the spinner
this list contains items which display into the spinner.Implement OnItemSelectedListener for Spinner
To handle the item selection of Spinner attaches onItemSelectedListener which implement 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
Full Source Code & Output.
activity_main.xmlcustom_spinner_layout.xml
MainActivity.java
CustomItems.java
CustomAdapter.java
If you have any questions or suggestions please leave them in the comments.
Full Source Code : https://github.com/Androchunk/CustomSpinner
Full Source Code : https://github.com/Androchunk/CustomSpinner
Question of the Day
Change Icon of Spinner like this,
Solution :
Official documentation:
AdapterView.OnItemSelectedListener:https://developer.android.com/reference/android/widget/AdapterView.OnItemSelectedListener
1 Comments
Good work sir,
ReplyDeletepublic CustomAdapter(@NonNull Context context, ArrayListcustomList) {
super(context,customList); } // I get a red line under the customList