Create a custom List using Custom Adapter

ArrayAdapter is a type of Adapter which acts a bridge between UI component and data source that helps us to fill data in UI component. It expects a Layout with a single TextView and for more customization in grid items or list items, we use custom adapters

  • ArrayAdapter is also an implementation of BaseAdapter so if we want more customization then we create a custom adapter and extend ArrayAdapter in that.
  • We override all the function’s of BaseAdapter in our custom adapter to give more customization to ArrayAdapter.

In the above code snippet we see the overrided functions of ArrayAdapter which are used to set the data in a list, grid or a spinner. From there we mainly used two functions getCount() and getView() .

1. getCount():

The getCount() function returns the total number of items to be displayed in a list. It counts the value from arraylist size or an array’s length.

2. getView(int i, View view, ViewGroup viewGroup):

This function is automatically called when the list item view is ready to be displayed or about to be displayed. In this function we set the layout for list items using LayoutInflater class and then add the data to the views like ImageView, TextView etc.

Example of Custom ArrayAdapter:

Step 1: Create a new project in Android Studio and name it CustomAdapterDemo.

  • Select File >> New >> New Project and Fill the forms and click “Finish” button.

Step 2: Now go to res -> layout -> xml (or) activity_main.xml and add following code. Here we are designing ListView in Relative Layout.

Step 3: Now Create a new Activity. Go to res >> right click on layout >> new >> Activity >> Blank Activity and create activity_design.xml activity. Here add following code. Here we are defining ImageView and TextView items that will be displayed inside each row of ListView.

Step 4: Now open app -> java -> package, click on MainActivity.java and add the below code. Here we will use CustomAdapter to display static data in XML layout. More explanation is included in the code itself.

Step 5: Create a new Class src -> package -> CustomAdapter.java and add the following code:

Step 6: Create a new Class src -> package -> DataModel.java and add the below code:

OutPut :-

 

About Jaimin Patel

I am a Web Developer. I have been blogging and researching since 1 years and like to share my knowledge and research with the world. Peace..!!

View all posts by Jaimin Patel →

Leave a Reply

Your email address will not be published. Required fields are marked *