This blog will explain you how to create Custom ListView in Android with BaseAdapter using ArrayList.

ListView

ListView is a view group that displays a list of vertical scrollable items. These items are automatically inserted to ListView using Adapter from the souProject Structurerce of Array or Database query.

Adapter

An Adapter is a bridge between Android’s UI component and Data Source by which UI components are filled. Adapter will holds list of records and send them to UI components to show on screen such as ListView, GridView, Spinner etc…

Prerequisites

  • Android Studio
  • Language Java

You have to have basic knowledge of creating application in Android Studio and Java language.

Please follow below steps to create ListView with Custom Adapter.

Step 1. Create Android Project with an empty Activity called MainActivity. As we have created Activity, two files activity_main.xml and MainActivity.java will be created in its correspondent folders. See project structure given at end of this blog. We will create our ListView in Main Activity.

Step 2. Open activity_main.xml , modify file with LinearLayout instead of RelativeLayout and set android:orientation property of LinearLayout to Vertical (android:orientation="vertical"). Now place ListView in LinearLayout and give proper ID to it. Your acitivity_main.xml file will look like,

acitivity_main.xml

<?xml version="1.0" encoding="utf-8"?>

  

<LinearLayout

    xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    tools:context="com.example.listviewcustomadapter.MainActivity">

  

    <ListView

        android:id="@+id/listViewData"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"></ListView>

  

</LinearLayout>

Step 3. Now create xml layout file which presents items to display in ListView. Simply it is a design file that shows how each item in ListView will display. Name a file with listinterface.xml.

Step to create xml Layout file: Right click to layout folder->New->Layout resource file.

listinterface.xml

<?xml version="1.0" encoding="utf-8"?>

  

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="horizontal">

  

    <ImageView

        android:id="@+id/imgLanguage"

        android:layout_width="90dp"

        android:layout_height="90dp"

        android:src="@drawable/anico" />

  

    <LinearLayout

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:orientation="vertical"

        android:padding="5dp">

  

        <TextView

            android:id="@+id/txtLanguageTitle"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="Dummy Text"

            android:textColor="#000000"

            android:textSize="18dp" />

        <TextView

            android:id="@+id/txtDesc"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="Dummy Text"

            android:textSize="12dp" />

  

    </LinearLayout>

  

</LinearLayout>

Step 4. Create a DataModel.java file which contains properties to set and get value of ArrayList.

Step to create java file: Right click to “com.example.listviewcustomadapter” inside java folder-> New-> Java Class.

DataModel.java

package com.example.listviewcustomadapter; /*Package name may vary from project to project*/

  

public class DataModel {

  

    private String LanguageTitle = "";

    private String Desc = "";

    private Integer imgSrc;

  

    public void setLanguageTitle(String _LanguageTitle) {

        this.LanguageTitle = _LanguageTitle;

    }

    public String getLanguageTitle() {

        return this.LanguageTitle;

    }

  

    public void setDesc(String _Desc) {

        this.Desc = _Desc;

    }

    public String getDesc() {

        return this.Desc;

    }

  

    public void setImgSrc(Integer _imgSrc) {

        this.imgSrc = _imgSrc;

    }

    public Integer getImgSrc() {

        return this.imgSrc;

    }

}

Step 5. Create a MyCustomAdapter.java file which will contain below code to fill adapter. Follow previous step to create java file.

Extend MyCustomAdapter class with BaseAdapter.

MyCustomAdapter.java

package com.example.listviewcustomadapter; /*Package name may vary from project to project*/

  

import android.content.Context;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.BaseAdapter;

import android.widget.ImageView;

import android.widget.TextView;

import java.util.ArrayList;

  

public class MyCustomAdapter extends BaseAdapter {

  

    ArrayList<DataModel> listDataModel = new ArrayList<DataModel>();

    LayoutInflater minflate;

  

    public MyCustomAdapter(ArrayList<DataModel> _listDataModel, Context context) {

        this.listDataModel = _listDataModel;

        this.minflate = LayoutInflater.from(context);

    }

  

    @Override

    public int getCount() {

        return listDataModel.size();

    }

  

    @Override

    public Object getItem(int position) {

        return listDataModel.get(position);

    }

  

    @Override

    public long getItemId(int position) {

        return position;

    }

  

    @Override

    public View getView(int position, View convertView, ViewGroup viewGroup) {

        ViewHolder vh;

        DataModel objDataModel = (DataModel) getItem(position);

        if (convertView == null) {

            convertView = minflate.inflate(R.layout.listinterface, null);

            vh = new ViewHolder();

            vh.txtLanguageTitle = (TextView) convertView.findViewById(R.id.txtLanguageTitle);

            vh.txtDesc = (TextView) convertView.findViewById(R.id.txtDesc);

            vh.imgLanguage = (ImageView) convertView.findViewById(R.id.imgLanguage);

            convertView.setTag(vh);

        } else {

            vh = (ViewHolder) convertView.getTag();

        }

        vh.txtLanguageTitle.setText(objDataModel.getLanguageTitle().toString());

        vh.txtDesc.setText(objDataModel.getDesc().toString());

        vh.imgLanguage.setImageResource(objDataModel.getImgSrc());

  

        return convertView;

    }

  

    public class ViewHolder {

        TextView txtLanguageTitle;

        TextView txtDesc;

        ImageView imgLanguage;

    }

}

Step 6. Now set MyCustomAdapter to ListView in MainAcity.java file. Follow below steps to write code in MainActivity.java.

  1. Open MainActivity.java.
  2. Create ArrayList of DataModel type.
  3. Fill Adapter with ArrayList.
  4. Bind ListView with Adapter in onCreate() event.

MainActivity.Java

package com.example.listviewcustomadapter; /* Package name may vary from project to project */

  

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.AdapterView;

import android.widget.ListView;

import android.widget.TextView;

import android.widget.Toast;

import java.util.ArrayList;

  

public class MainActivity extends AppCompatActivity {

  

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

  

        ArrayList<DataModel> _liDataModel = listArray();

  

        ListView listViewData = (ListView) findViewById(R.id.listViewData);

        listViewData.setAdapter(new MyCustomAdapter(_liDataModel, this));

        /* Set ListView Item Click Listener */

        listViewData.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override

            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

  

                /* 1. Get clicked item value by AdapterView */

                DataModel selectedItem = (DataModel) adapterView.getItemAtPosition(position);

                Toast.makeText(MainActivity.this, selectedItem.getLanguageTitle().toString(), Toast.LENGTH_SHORT).show();

  

                /* 2. Get clicked item value by finding TextView */

                TextView txtLanguageTitle = (TextView) view.findViewById(R.id.txtLanguageTitle);

                Toast.makeText(MainActivity.this, txtLanguageTitle.getText().toString(), Toast.LENGTH_SHORT).show();

  

            }

        });

    }

  

    public ArrayList<DataModel> listArray() {

  

        ArrayList<DataModel> objList = new ArrayList<DataModel>();

        DataModel dm;

  

        dm = new DataModel();

        dm.setLanguageTitle("Android");

        dm.setDesc("Hello, I am Android..!! I am Mobile Application Development Platform..!!");

        dm.setImgSrc(R.drawable.anico);

        objList.add(dm);

  

        dm = new DataModel();

        dm.setLanguageTitle(".NET");

        dm.setDesc("Hello, I am .NET..!! I am Web Application Development Platform..!!");

        dm.setImgSrc(R.drawable.netico);

        objList.add(dm);

  

        dm = new DataModel();

        dm.setLanguageTitle("iOS");

        dm.setDesc("Hello, I am iOS..!! I am Mobile Application Development Platform..!!");

        dm.setImgSrc(R.drawable.iosico);

        objList.add(dm);

  

        dm = new DataModel();

        dm.setLanguageTitle("PHP");

        dm.setDesc("Hello, I am PHP..!! I am Web Application Development Platform..!!");

        dm.setImgSrc(R.drawable.phpico);

        objList.add(dm);

  

        dm = new DataModel();

        dm.setLanguageTitle("JAVA");

        dm.setDesc("Hello, I am JAVA..!! I am Web Application Development Platform..!!");

        dm.setImgSrc(R.drawable.javaico);

        objList.add(dm);

  

        dm = new DataModel();

        dm.setLanguageTitle(".NET");

        dm.setDesc("Hello, I am .NET..!! I am Web Application Development Platform..!!");

        dm.setImgSrc(R.drawable.netico);

        objList.add(dm);

  

        return objList;

    }

}

ListView Item Click Listener

Click event of item inside ListView can be taken using setOnItemClickListener() method of ListView. You can see my ListView itemclicklistener in onCreate() method.

listViewData.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    @Override

    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

  

        /* 1. Get clicked item value by AdapterView */

        DataModel dmSelectedItem = (DataModel) adapterView.getItemAtPosition(position);

        Toast.makeText(MainActivity.this, dmSelectedItem.getLanguageTitle().toString(), Toast.LENGTH_SHORT).show();

  

        /* 2. Get clicked item value by finding TextView */

        TextView txtLanguageTitle = (TextView) view.findViewById(R.id.txtLanguageTitle);

        Toast.makeText(MainActivity.this, txtLanguageTitle.getText().toString(), Toast.LENGTH_SHORT).show();

  

    }

});

There are two ways to get the value of the item on which the user has clicked which is given below. You can use any of one from it.

1. Using AdapterView: To get the value of clicked item using AdapterView wee has to use adapterView.getItemAtPosition(position) method. See my code.

DataModel selectedItem = (DataModel) adapterView.getItemAtPosition(position);

2. Using findViewById: In this, we have to use view.findViewById() method and find TextView of its Interface file and get its text.

TextView txtLanguageTitle = (TextView) view.findViewById(R.id.txtLanguageTitle);

Now run this application in AVD or in your mobile. The output screen shown below.

Output

Your Project Structure may look like,

I hope you like this blog. If you have any query, please comment below. Thank You… :)