ListView Tutorial With Example In Android Studio

List of scrollable items can be shown in Android using ListView. It helps you to showing the information as a scrollable list. Users would then be able to choose any list item by clicking on it. ListView is default scrollable so we don’t have to use scroll View or whatever else with ListView.

ListView is broadly used as a part of android applications. An exceptionally normal case of ListView is your phone contact book, where you have a list of your contacts showed in a ListView and if you click on it then user information is shown.

Android ListView Tutorial With Example – Android Studio

Download projct file of  ListView Tutorial With Example – Android Studio

Adapter: To fill the data in a ListView we simply use adapters. List items are automatically inserted to a list using an Adapter that pulls the content from a source such as an arraylist, array or database.

ListView in Android Studio: Listview is present inside Containers. From there you can drag and drop on virtual mobile screen to create it. Alternatively you can also XML code to create it.

item1

 

Here is Android ListView XML Code:

<ListView
    android:id="@+id/ListView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:divider="@color/material_blue_grey_800"
    android:dividerHeight="1dp" />

Listview look in Design:

item5

In android commonly used adapters are:

  1. Array Adapter
  2. Base Adapter

Now we explain these two adapter in details:

Important Note: By default, ArrayAdapter expects a Layout with a single TextView, If you want to use more complex views means more customization in list items, please avoid ArrayAdapter and use custom adapters.

Below is Array Adapter code:

ArrayAdapter adapter = new ArrayAdapter<String>(this,R.layout.ListView,R.id.textView,StringArray);

Example of list view using Array Adapter:

In this example, we display a list of countries by using simple array adapter. Below is the final output we will create:

iteme3

 

 

Step 1: Create a new project Listexample and activity Main Activity. Here we will create a ListView in LinearLayout. Below is the code of activity_main.xml or content_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.andrious.listview.MainActivity">

    <ListView
        android:id="@+id/ListView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:divider="@color/material_blue_grey_800"
        android:dividerHeight="1dp" />

</LinearLayout>

Step 2: Create a new activity name Listview and below is the code of activity_list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:padding="10dp"
        android:text="fruit list"
        android:textColor="#000000" />

</LinearLayout>

Step 3: Now in this final step we will use ArrayAdapter to display the country names in UI. Below is the code of MainActivity.java

package com.andrious.listview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {
    // Array of strings...
    ListView simpleList;
    String  FruitList[] = {"Apple", "Banana", "Lemon", "Cherry", "Strawberry", "Avocado"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        simpleList = (ListView)findViewById(R.id.ListView);
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.activity_list_item, R.id.textView, FruitList);
        simpleList.setAdapter(arrayAdapter);
    }
}

Output Screen:

Now run the App in Emulator. You will see the below output screen where list of fruits names will be printed:

iteme3

 

2.Base Adapter:

BaseAdapter is a common base class of a general implementation of an Adapter that can be used in ListView. Whenever you need a customized list you create your own adapter and extend base adapter in that. Base Adapter can be extended to create a custom Adapter for displaying a custom list item.  ArrayAdapter is also an implementation of BaseAdapter.

 Example of list view using Custom adapter(Base adapter):

In this example we display a list of countries with flags. For this, we have to use custom adapter as shown in example:

item4

Step 1: Create a new project Listebasexample and activity Main Activity. Here we will create a ListView in LinearLayout. Below is the code of activity_main.xml or content_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.andrious.listview.MainActivity">

    <ListView
        android:id="@+id/ListView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:divider="@color/material_blue_grey_800"
        android:dividerHeight="2dp"
        android:footerDividersEnabled="false"/>

</LinearLayout>

Step 2: Create a new activity name Listview and below is the code of activity_list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:orientation="horizontal"
        android:weightSum="4">
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1">
            <ImageView
                android:id="@+id/image"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="fitXY"
                android:src="@mipmap/ic_launcher" />
        </LinearLayout>
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:layout_weight="3"
            android:weightSum="3">
            <TextView
                android:id="@+id/item"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:layout_gravity="center"
                android:text="Fruit name"
                android:textStyle="bold"
                android:textColor="#000000" />
            <TextView
                android:id="@+id/subitem"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="2"
                android:layout_gravity="center"
                android:text="fruit list"
                android:textSize="12dp"
                android:textColor="#000000" />
        </LinearLayout>
    </LinearLayout>    
</LinearLayout>

Step 3: In third step we will use custom adapter to display the country names in UI by coding MainActivity.java. Below is the code of MainActivity.java

Important Note: Make sure flag images are stored in drawable folder present inside res folder with correct naming.

package com.andrious.listview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {
    // Array of strings...
    ListView simpleList;
    String  Item[] = {"Apple", "Banana", "Lemon", "Cherry", "Strawberry", "Avocado"};
    String  SubItem[] = {"The apple tree is a deciduous tree in the rose family best known for its sweet, pomaceous fruit, the apple.",
            "The banana is an edible fruit – botanically a berry – produced by several kinds of large herbaceous flowering plants in the genus Musa.",
            "The lemon, Citrus limon Osbeck, is a species of small evergreen tree in the flowering plant family Rutaceae, native to Asia.",
            "A cherry is the fruit of many plants of the genus Prunus, and is a fleshy drupe.",
            "The garden strawberry is a widely grown hybrid species of the genus Fragaria, collectively known as the strawberries.",
            "The avocado is a tree, long thought to have originated in South Central Mexico, classified as a member of the flowering plant family Lauraceae."};
    int flags[] = {R.drawable.apple, R.drawable.banana, R.drawable.lemon, R.drawable.cherry, R.drawable.strawberrie, R.drawable.avocado};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        simpleList = (ListView)findViewById(R.id.ListView);
        CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), Item,SubItem, flags);
        simpleList.setAdapter(customAdapter);
    }
}

Step 4: Now create another class Custom Adapter which will extend BaseAdapter. Below is the code of CustomAdapter.java

package com.andrious.listview;

/**
 * Created by MD.ISRAFIL MAHMUD on 12/27/2017.
 */
import android.content.Context;
import android.media.Image;
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.zip.Inflater;

public class CustomAdapter extends BaseAdapter {
    Context context;
    String Item[];
    String SubItem[];
    int flags[];
    LayoutInflater inflter;

    public CustomAdapter(Context applicationContext, String[] Item, String[] SubItem , int[] flags) {
        this.context = context;
        this.Item = Item;
        this.SubItem = SubItem;
        this.flags = flags;
        inflter = (LayoutInflater.from(applicationContext));
    }

    @Override
    public int getCount() {
        return Item.length;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        view = inflter.inflate(R.layout.activity_list_item, null);
        TextView item = (TextView) view.findViewById(R.id.item);
        TextView subitem = (TextView) view.findViewById(R.id.subitem);
        ImageView image = (ImageView) view.findViewById(R.id.image);
        item.setText(Item[i]);
        subitem.setText(SubItem[i]);
        image.setImageResource(flags[i]);
        return view;
    }
}

Output:

Now run the App in Emulator and it will show you name of countries along with flags. Below is the output screen:

item4

3 Comments

  1. Justin Marcet

    June 19, 2018 at 1:38 pm

    you’re in reality a excellent webmaster. The site loading pace is amazing. It kind of feels that you’re doing any distinctive trick. Moreover, The contents are masterwork. you’ve done a magnificent job on this matter!

  2. Julianne Schnabel

    August 30, 2018 at 6:44 am

    With thanks! Valuable information!

  3. car removals

    September 20, 2018 at 4:27 am

    Thank you for all your work on this site. Debby delights in making time for research and it’s really obvious why. We all notice all about the powerful means you present invaluable strategies on your web blog and even inspire response from other people on that issue so my child is without question studying a lot of things. Have fun with the rest of the year. You are always performing a great job.

Leave a Reply