Using Custom Adapter with Spinner
In this example , we will be using a Custom Adapter to diaply data in a Spinner. Whenever user clicks on the Spinner all the entries show up in the dropdown with respective image and text in every unit of Spinner row.
Steps to develop this can be summarized below -
- Make a new project with Empty Activity.
- Add two arrays - one for names another for respective images
- Create a new Custom Adapter( MyAdapter.class) which extends ArrayAdapter
- Use this new Adapter to connect the data source and Spinner
- We put a Spinner in the layout for the launch activity
- Implement OnItemSelectedListener on the spinner object to detect any clicks on spinner
- We also need to implement the onNothingSelected though we dont use it.
- Prepare a layout for indivdual row to design the individual row of the spinner.
- In the MyAdapter, we need to prepare a constructor to create objects(views) for the spinner.
- We override 2 methods here - getView and getDropDownView
- getView() is called whenever a view is required to be displayed.
- getDropDownView() is called when spinner is opened
- Both these methods eventually call getCustomView() which is responsible for eventually generating Views.
Used Concepts & Used Version:
- compileSdkVersion 24
- buildToolsVersion "25.0.0"
Now, let’s begin the development...
1.MainActivity (Launcher Activity)
2. Layout for MainActivity.class
3. row.xml (For every unit of Spinner)
MyAdapter.class
Below Screenshots for the output.