Android Custom Spinner - Androchunk

So Far you learn how to create Spinner and change the color of the spinner in android.
In this post, you learn how to create a custom spinner in android.



Steps to create a custom Spinner

  1. Create a Spinner Element in your XML file.
  2. Create the custom layout for Spinner element.
  3. Create the Getter/Setter method for Spinner element.
  4. Create Adapter for the Spinner.
  5. Create Item List for the spinner.
  6. Implement OnItemSelectedListener for Spinner.
  7. 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.xml

custom_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


Question of the Day

  Change Icon of Spinner like this,


Solution :


Official documentation:




 

Post a Comment

1 Comments

  1. Good work sir,

    public CustomAdapter(@NonNull Context context, ArrayListcustomList) {
    super(context,customList); } // I get a red line under the customList

    ReplyDelete