Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
The Syntax
3.
Implementation of ListView
3.1.
Creating an Android Studio Project
3.2.
The main activity XML file
3.3.
The main activity Kotlin file
3.4.
The Android Manifest XML file
3.5.
The Resources directory
4.
Final List View
5.
FAQs
6.
Key Takeaways
Last Updated: Mar 27, 2024
Easy

List View in Android

Author Vasu Bansal
0 upvote
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

In this blog, you will learn about the ListView widget, which is commonly used in Android applications. Understanding the concept of widgets and user interface (UI) is necessary before proceeding further in the blog. The user interface refers to the frontend or the screen with which the user interacts directly. Widgets are the elements of this user interface that helps provide a smooth interface for the users. 

The Syntax

ListView is a widget that helps the developer display a list of things on the application screen. There are a lot of properties associated with ListView, such as divider, divider height, entries, etc. The following is the class syntax of ListView.

public class ListView
extends AbsListView

The class hierarchy of ListView is as follows.

java.lang.Object
|-> android.view.View
 |-> android.view.ViewGroup
  |-> android.widget.AdapterView<android.widget.ListAdapter>
   |-> android.widget.AbsListView
    |-> android.widget.ListView 

There are many other widgets available in android. To learn about TextView in Android development, refer to the blog TextView on the Coding Ninjas Website.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Implementation of ListView

Creating a ListView is a simple and straightforward process. Just follow the simple steps given in below to make your first ListView.

Creating an Android Studio Project

You need to first create an Android Studio project before actually creating your Android apps. To create a new project, open up Android Studio and press the New Project button, select Empty Activity as the activity type, and the implementation language as Kotlin. Select a minimum SDK version as per your requirements.

Don't have Android Studio and environment already set up in your machine? No worries, we got you all covered. Refer to the blog Android Studio and Environment Setup on the Coding Ninjas Website to set up things for a smoother development process.

The main activity XML file

The activity_main.xml file is the most important layout of your application which is referenced when we are building the interface of our application. The code for the ListView widget is written in this file. 

Code:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

In this file, we have defined a ListView with id as list. The properties such as layout_width and layout_height are also set and given the value of match_parent.

The main activity Kotlin file

This is the main file that gets your application running. This file contains the onCreate method, one of the first methods that get called after running our application. The code for MainActivity.kt file is given as below.

Code:

package com.example.listview

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.TextView
import android.widget.Toast
import java.util.ArrayList

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val my_list_view = findViewById<ListView?>(R.id.list)
        val blogs = ArrayList<String?>()
        blogs.add("Kotlin")
        blogs.add("Java")
        blogs.add("Android")
        blogs.add("Networks")
        blogs.add("DSA")
        blogs.add("OOPs")
        val arr = ArrayAdapter(
            this,
            android.R.layout.simple_list_item_1,
            blogs
        )
        my_list_view.adapter = arr
        my_list_view.setOnItemClickListener { adapterView, view, i, l ->
            val display_text = (view as TextView).text.toString() + " Selected"
            Toast.makeText(this@MainActivity, display_text, Toast.LENGTH_SHORT).show()
        }
    }
}

Inside the onCreate() method, we call the function findViewById and pass to it an argument of R.id.list (note from the above section, we had given the ID of the ListView as list, so the list comes from there)After that, we have created a local variable named blogs which stores an ArrayList of Strings. In the following step, we create an instance of ArrayAdapter and pass the required parameters to it and save this instance in the adapter of the my_list_view. At last, we associate a setOnItemClickListener with each click on the items of the list. Inside this, we use the Toast library to display the text on the application screen.

The Android Manifest XML file

This file is used for registering our activities. We don’t need to change anything in this file and just use the boilerplate code provided by Android Studio for this. The code for the AndroidManifest.xml file is given below.

Code:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.listview">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.ListView">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

The Resources directory

The resources folder named res in our Android Studio project is an important folder that contains all the resources for our application. It contains all non-coding assets of our application. For example, consider the strings.xml file present under the directory res/values. This file contains the name of the application, which is rendered when we run the application. The code of this file is written below. In this blog, we have named the application as ListView.

Code:

<resources>
    <string name="app_name">ListView</string>
</resources>

Final List View

The final list view that will be created after following this blog will look as follows.

When you press any item of the list, for example, Android, the application will give a notification as Android selected.

FAQs

  1. Which attribute of the ListView is used to specify the reference to array resources that populate the ListView?
    Ans: The android:entries attribute is used to specify the reference to array resources that populate the ListView.
     
  2. What is the use of the android:headerDividersEnabled attribute in the XML file? 
    Ans: This property takes a boolean value. The ListView does not draw a divider line after each header if this value is set to false. The default value for this property is true.
     
  3. What is the use of the setAdapter() function in ListView?
    Ans: The setAdapter() function is used to associate an adapter with a list view instance. It helps the application display the items of a list.

Key Takeaways

In this article, we have extensively discussed List Views in Android along with a sample application containing the implementation of a sample List View. You can also read the blog Navigation Drawer on the Coding Ninjas Website to create Navigation Drawers in your Android application.

We hope that this blog has helped you enhance your knowledge regarding List Views and if you would like to learn more, check out our Android Development Course on the Coding Ninjas Website to learn everything you need to know about Android development. Do upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass