Android Custom ListView Tutorial with ImageView and TextViews using Android Studio

2
20
android custom list view

Note: Android RecyclerView is the most advanced version of ListView. You can refer to the article on Android RecyclerView here.

In  our previous article we have discussed about how to implement Android Simple Listview. In this article we are going to discuss about android custom listview implementation with an image and text using New Android Studio 1.5.1.

In this tutorial, we are going to display a country name, its flag, its capital and currency in a listview and when a user clicks on a list item, he is taken to another activity which displays the particular country’s details. Lets get started:android custom listview

Creating Android Custom ListView:

First let us start creating Android Custom ListView by integrating the required images and colors. You can get the required images and source code from the link below:

[wpdm_package id=’785′]

Let us start by creating a single list item which we will populate in a listview. Now create an xml File in Res > Layout and name it as list_item.xml. Now type the following code:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="6dp"
    android:paddingTop="6dp"
    android:paddingBottom="6dp"
    android:orientation="vertical">



    <!--Flag Image-->
    <ImageView

        android:id="@+id/ivFlag"
        android:layout_width="60dp"
        android:layout_height="40dp"
        android:src="@drawable/flag_india"
        android:layout_alignTop="@+id/linearLayout"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <!--Country Name-->
    <TextView
        android:id="@+id/tvCountryName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAllCaps="true"
        android:layout_centerHorizontal="true"
        android:text="India"
        android:textSize="15dp"
        android:layout_centerInParent="true"
        android:gravity="center"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:id="@+id/linearLayout">
        <TextView
            android:id="@+id/tvCapitalHead"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="12sp"
            android:text="Capital:  "
            android:textStyle="bold" />

        <TextView
            android:id="@+id/tvCapital"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="12sp"
            android:text="New Delhi" />


    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true">
        <TextView
            android:id="@+id/tvCurrencyHead"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Currency:  "
            android:textSize="12sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/tvCurrency"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="12sp"
            android:text="Rupee" />


    </LinearLayout>


</RelativeLayout>

Images inside drawable can be obtained from the source code attached to this article.

Adding the required images:

All the images used in the code can be downloaded from the source code attached to this tutorial. You can download and paste them in your drawable folder.

Adding the required Strings:

Open res > values > strings.xml file and type the following code:

<resources>
    <string name="app_name">CustomListViewTutorial</string>
    <string name="action_settings">Settings</string>
    <string name="details_india">One-third the area of the United States, the Republic of India occupies most of the subcontinent of India in southern Asia. It borders on China in the northeast. Other neighbors are Pakistan on the west, Nepal and Bhutan on the north, and Burma and Bangladesh on the east.

The country can be divided into three distinct geographic regions: the Himalayan region in the north, which contains some of the highest mountains in the world, the Gangetic Plain, and the plateau region in the south and central part. Its three great river systems—the Ganges, the Indus, and the Brahmaputra—have extensive deltas and all rise in the Himalayas.</string>

    <string name="details_australia">The continent of Australia, with the island state of Tasmania, is approximately equal in area to the United States (excluding Alaska and Hawaii). Mountain ranges run from north to south along the east coast, reaching their highest point in Mount Kosciusko (7,308 ft; 2,228 m). The western half of the continent is occupied by a desert plateau that rises into barren, rolling hills near the west coast. The Great Barrier Reef, extending about 1,245 mi (2,000 km), lies along the northeast coast. The island of Tasmania (26,178 sq mi; 67,800 sq km) is off the southeast coast</string>
    <string name="details_china">The greater part of the country is mountainous. Its principal ranges are the Tien Shan, the Kunlun chain, and the Trans-Himalaya. In the southwest is Tibet, which China annexed in 1950. The Gobi Desert lies to the north. China proper consists of three great river systems: the Yellow River (Huang He), 2,109 mi (5,464 km) long; the Yangtze River (Chang Jiang), the third-longest river in the world at 2,432 mi (6,300 km); and the Pearl River (Zhu Jiang), 848 mi (2,197 km) long.</string>
    <string name="details_indonesia">Indonesia is an archipelago in Southeast Asia consisting of 17,000 islands (6,000 inhabited) and straddling the equator. The largest islands are Sumatra, Java (the most populous), Bali, Kalimantan (Indonesia\'s part of Borneo), Sulawesi (Celebes), the Nusa Tenggara islands, the Moluccas Islands, and Irian Jaya (also called West Papua), the western part of New Guinea. Its neighbor to the north is Malaysia and to the east is Papua New Guinea.

Indonesia, part of the “ring of fire,” has the largest number of active volcanoes in the world. Earthquakes are frequent. Wallace\'s line, a zoological demarcation between Asian and Australian flora and fauna, divides Indonesia.</string>
    <string name="details_japan">An archipelago in the Pacific, Japan is separated from the east coast of Asia by the Sea of Japan. It is approximately the size of Montana. Japan\'s four main islands are Honshu, Hokkaido, Kyushu, and Shikoku. The Ryukyu chain to the southwest was U.S.-occupied from 1945 to 1972, when it reverted to Japanese control, and the Kurils to the northeast are Russian-occupied.</string>
    <string name="details_newzealand">New Zealand, about 1,250 mi (2,012 km) southeast of Australia, consists of two main islands and a number of smaller outlying islands so scattered that they range from the tropical to the antarctic. The country is the size of Colorado. New Zealand\'s two main components are the North Island and the South Island, separated by Cook Strait. The North Island (44,281 sq mi; 115,777 sq km) is 515 mi (829 km) long and volcanic in its south-central part. This area contains many hot springs and beautiful geysers. South Island (58,093 sq mi; 151,215 sq km) has the Southern Alps along its west coast, with Mount Cook (12,316 ft; 3754 m) the highest point. Other inhabited islands include Stewart Island, the Chatham Islands, and Great Barrier Island. The largest of the uninhabited outlying islands are the Auckland Islands (234 sq mi; 606 sq km), Campbell Island (44 sq mi; 114 sq km), the Antipodes Islands (24 sq mi; 62 sq km), and the Kermadec Islands (13 sq mi; 34 sq km).</string>
    <string name="details_russia">The Russian Federation is the largest of the 21 republics that make up the Commonwealth of Independent States. It occupies most of eastern Europe and north Asia, stretching from the Baltic Sea in the west to the Pacific Ocean in the east, and from the Arctic Ocean in the north to the Black Sea and the Caucasus in the south. It is bordered by Norway and Finland in the northwest; Estonia, Latvia, Belarus, Ukraine, Poland, and Lithuania in the west; Georgia and Azerbaijan in the southwest; and Kazakhstan, Mongolia, China, and North Korea along the southern border.</string>
    <string name="details_southkorea">Slightly larger than Indiana, South Korea lies below the 38th parallel on the Korean peninsula. It is mountainous in the east; in the west and south are many harbors on the mainland and offshore islands.</string>
</resources>

Adding required color values:

Now open res > values >colors.xml file and type the following code in it:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#E91E63</color>
    <color name="colorPrimaryDark">#C2185B</color>
    <color name="colorAccent">#FF4081</color>



    <color name="tabsScrollColor">#2097ff</color>
    <color name="list_divider">#d9d9d9</color>
    <color name="list_row_start_color">#ffffff</color>
    <color name="list_row_end_color">#ffffff</color>
    <color name="list_row_hover_start_color">#ebeef0</color>
    <color name="list_row_hover_end_color">#1c9ef4</color>

</resources>

Now we create model class in Java. Let us create a model folder by right clicking on package and create a model class named Country.java. Now add the following code to it:

package com.coderefer.customlistviewtutorial.model;

/**
 * Created by vamsitallapudi on 25-Dec-15.
 */
public class Country {

    private String name, capital, currency;
    private int flag;

    public Country() {
    }

    public Country(String name, int flag, String capital, String currency) {
        this.name = name;
        this.flag = flag;
        this.capital = capital;
        this.currency = currency;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getFlag() {
        return flag;
    }

    public void setFlag(int flag) {
        this.flag = flag;
    }

    public String getCapital() {
        return capital;
    }

    public void setCapital(String capital) {
        this.capital = capital;
    }

    public String getCurrency() {
        return currency;
    }

    public void setCurrency(String currency) {
        this.currency = currency;
    }
}

Now we create a custom Adapter for our our ListView. Here I created a folder named adapter inside my package and created a class named CountryListAdapter.java to use as Custom Adapter, with the following code:

package com.coderefer.customlistviewtutorial.adapter;

import android.app.Activity;
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 com.coderefer.customlistviewtutorial.R;
import com.coderefer.customlistviewtutorial.model.Country;

import java.util.List;

/**
 * Created by vamsitallapudi on 25-Dec-15.
 */
public class CountryListAdapter extends BaseAdapter {

    private Activity activity;
    private List<Country> countryList;
    private LayoutInflater inflater;

    public CountryListAdapter(Activity activity, List<Country> countryList){
        this.activity = activity;
        this.countryList = countryList;
    }

    @Override
    public int getCount() {
        return countryList.size();
    }

    @Override
    public Object getItem(int position) {
        return countryList.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if(inflater == null){
            inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }if(convertView == null){
            convertView = inflater.inflate(R.layout.list_item, null);
        }
        ImageView flag = (ImageView) convertView.findViewById(R.id.ivFlag);
        TextView name  = (TextView) convertView.findViewById(R.id.tvCountryName);
        TextView capital = (TextView) convertView.findViewById(R.id.tvCapital);
        TextView currency = (TextView) convertView.findViewById(R.id.tvCurrency);

        Country country = countryList.get(position);
        flag.setImageResource(country.getFlag());
        name.setText(country.getName());
        capital.setText(country.getCapital());
        currency.setText(country.getCurrency());

        return convertView;
    }
}

Now open res > layout >content_main.xml. If the file is missing, create a file with name content_main.xml and add the following code to it:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="wrap_content"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.coderefer.customlistviewtutorial.MainActivity"
    tools:showIn="@layout/activity_main">

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:divider="@color/list_divider"
        android:dividerHeight="1dp"
        android:listSelector="@drawable/list_row_selector" />

</RelativeLayout>

Here we added our Android Custom Listview to content_main.xml

Now we will open our activity_main.xml file and add the following code to it:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
    tools:context="com.coderefer.customlistviewtutorial.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height = "?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <!--Including content_main.xml layout in activity_main.xml-->
    <include layout="@layout/content_main" />

</android.support.design.widget.CoordinatorLayout>

Now we modify the MainActivity.java as follows:

package com.coderefer.customlistviewtutorial;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ListView;

import com.coderefer.customlistviewtutorial.adapter.CountryListAdapter;
import com.coderefer.customlistviewtutorial.model.Country;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private List<Country> countryList = new ArrayList<>();
    private CountryListAdapter countryListAdapter;

    private ListView listView;

    String[] countryNames = new String[]{
            "India", "Australia","China", "Indonesia", "Japan", "Newzealand","Russia","South Korea"
    };
    int[] flagId = new int[]{
            R.drawable.flag_india, R.drawable.flag_australia,R.drawable.flag_china,R.drawable.flag_indonesia,
            R.drawable.flag_japan,R.drawable.flag_newzealand,R.drawable.flag_russia,R.drawable.flag_southkorea
    };
    String[] capital = new String[]{
      "New Delhi", "Sydney", "Beijing","Jakarta", "Tokyo", "Wellington", "Moscow", "Seoul"
    };

    String[] currency = new String[]{
      "Rupee", "Dollar", "Renminbi","Rupiah",
            "Yen","Dollar","Ruble","Won"
    };

    int[] details = new int[]{
            R.string.details_india,R.string.details_australia,R.string.details_china,
            R.string.details_indonesia,R.string.details_japan,R.string.details_newzealand,
            R.string.details_russia,R.string.details_southkorea
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        listView = (ListView) findViewById(R.id.list);
        //Custom ListAdapter for our android custom listview
        countryListAdapter = new CountryListAdapter(this, countryList);
        //Setting ListView's adapter to the custom list adapter we've created
        listView.setAdapter(countryListAdapter);



        for (int i = 0;i<countryNames.length;i++){
            Country country = new Country();
            country.setName(countryNames[i]);
            country.setCapital(capital[i]);
            country.setFlag(flagId[i]);
            country.setCurrency(currency[i]);
            countryList.add(country);
        }

        //Open a new activity when a list item from android custom listview is clicked.
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Declaring Intent
                Intent i = new Intent(MainActivity.this, DetailActivity.class);
                //Putting required data in intent
                i.putExtra("flag",flagId[position]);
                i.putExtra("details", details[position]);
                startActivity(i);
            }
        });


    }


}

Here we added an instance of countryListAdapter in our onCreate() method and set the listview’s adapter as countryListAdapter.

Next, to start another activity when a list item is clicked, we called setOnItemClickListener() on listView and called another Activity named DetailActivity which we are going to create now.

First we edit activity_detail.xml and add the following code to it:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.coderefer.customlistviewtutorial.DetailActivity">
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/ivDetails"
        android:src="@drawable/flag_india"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/details_india"
        android:textSize="17sp"
        android:id="@+id/tvDetails"
        android:layout_below="@+id/ivDetails"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

Here we just added an imageview and textview in our android custom listview to display the country’s flag and country’s details in brief.

We next create a file named DetailActivity.java and add the following code to it:

package com.coderefer.customlistviewtutorial;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

public class DetailActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        TextView tvDetails = (TextView) findViewById(R.id.tvDetails);
        ImageView ivDetails = (ImageView) findViewById(R.id.ivDetails);

        Intent i = getIntent();
        //retriving data from intents and setting it to textview and imageview
        ivDetails.setImageResource(i.getIntExtra("flag", R.drawable.flag_india));
        tvDetails.setText(i.getIntExtra("details", R.string.details_india));
    }
}

Here we retrieved the data from intent and set it to the textview and imageview from activity_detail.xml.

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
Annabel TengJonathan Recent comment authors

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
newest oldest most voted
Notify of
Jonathan
Guest
Jonathan

Really nice was searching for sample for listview with image since a while.

Annabel Teng
Guest
Annabel Teng

could you update this also? Source code not available to download?