Android ListView

A kind of AdapterView that displays a vertical list of scrollable views, each of which is laid out below each other is called ListView. Using adapters, items are inserted into the view from an array list or a database. setAdaptor() is used to display items in the list method. The setAdaptor() method associates a/n adapter with a list.

Android ListView ViewGroup is used to display a list of items on multiple lines, with an adapter to automatically insert items into the list. The main task of the adapter is to retrieve from an array list or a databaseand put each item into a list to get the expected result. Therefore, it is the main source of importing data from a strings.xml file that contains all the required strings from a Java or XML file.

ArrayAdapter

This adapter can be used when an array is the data source. Basically, the ArrayAdapter calls the toString() method on each item and puts its data into a TextView, creating a view of each array item. If you have an array of strings to display in the ListView, use the constructor to initialize a new ArrayAdapter and specify the layout of each string and the string array.

ArrayAdapter adapter = new ArrayAdapter<String>(this,R.layout.ListV,StrArrayList);

The arguments to this constructor are: -

  • Application context is the first argument that needs to be passed. ‘this’ is passed most of the time.
  • The second argument is a layout with a TextView for each string in the array defined in the XML file.
  • An array of strings to be entered into the textview is the last argument. After creating thearray adapter, I just call setAdapter() on the ListView object like this -
ListView listVi = findViewById(R.id.listv);
listVi.setAdapter(adapter);

The List view will be declared in an XML filein the res/layout directory. For our demonstration, we are going to using the activity_listview.xml file.

ListView XML Attributes

  • android:divider-A color or drawable for separating list items.
  • android:dividerHeight-Property to specify divider’s height.
  • android:footerDividersEnabled-The ListView will draw the divider before each footer view when set to true.
  • android:headerDividersEnabled-The ListView will draw the divider before each header view when set to true.
  • android:entries- Refer to an array resource that will fill the ListView with the items.

Android ListView Click Processing

To handle the click of an Android ListView item, the onListItemClick() method is used. This method takes four arguments-

  • ListView: ListView containing the display of items
  • View: View of the specific item selected
  • Position: The position of the item selected from the array. Recall that the first item in the array is at position 0 because the array index starts from 0.
  • Id: ID of the selected item. In the tutorial, it's not important, but it's important if you want to use the data retrieved from the database because you can use id (the ID of the row that contains the item in the database) to retrieve the item from the database.

Demonstration of adding ListView

Here's a demonstration of implementing a simple ListView in an Android application. In the demonstration, let’s build an android application that will display a list of the different fast foods we like to eat.

1. In Android Studio, make a new project and name it as ListView Example. If you come across any problem in creating a new project, please refer to Android Studio Tutorial. Remembertochoose the Java language.

2. Insert a ListView in the activity_main.xml file and the XML code is as follows:

<?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=".Javatpoint.ListViewActivity">


<ListView
android:id="@+id/FoodList"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

3. In this step, let's design the backend of our application. Go to ListViewActivity.java. The following creates an array of strings in a Java file and stores the values to display in the list. It also creates a ListView class object. I use findViewById() method in onCreate() method to retrieve ListView by id. Using the new keyword, make an ArrayAdapter object followed by a constructor call.

package com.example.myapplication.Javatpoint;


import androidx.appcompat.app.AppCompatActivity;


import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;


import com.example.myapplication.R;


public class ListViewActivity extends AppCompatActivity {


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


ListView lv;
String foodArray[]
                = {"Pizza", "Burger",
"Pasta", "Chicken",
"Spaghetti", "Noodles",
"Garlic Bread"};


lv = findViewById(R.id.FoodList);
ArrayAdapter<String>arr;


arr = new ArrayAdapter<String>(
this,
R.layout.support_simple_spinner_dropdown_item,
foodArray);
lv.setAdapter(arr);


lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {


String value=arr.getItem(position);
Toast.makeText(getApplicationContext(),value,Toast.LENGTH_SHORT).show();
            }
        });
    }
}

ListView Output

Android ListView

Related Topics

Android ScrollView

A ScrollView is a view group that is used to create vertically scrollable views in an android application. Only a single direct child can be contained by ScrollView. For placing...

5 minutes read.

Dashboard UI Design in Android

One of the essential components that draw the user’s attentions into the application's operation is the dashboard design. It offers details on the application's general functionality in one location. Imagine...

11 minutes read.

ImageView Widget in Android

What you should already KNOW? You should be familiar with: 1) Creating, building, and running apps in Android Studio 2) Basics of android widgets Explanation: Image View widget is used to insert the image...

2 minutes read.

Android Emulator

A tool for creating Android virtual devices (including software and virtual hardware) on your personal desktop is known as Emulator. We can use these virtual devices as the target device...

4 minutes read.

How to show image on an android application

ImageView Widget in Android What you should already KNOW? You should be familiar with: 1) Creating, building, and running apps in Android Studio 2) Basics of android widgets   Explanation: Image View widget is used...

2 minutes read.

How to insert an email in android application in android version 8

Email Address Insertion It is used to insert email adrress from the user in the android application.The only point of difference between an EditText and an Emailtext is that EmailText consisits...

1 minute read.

How to reduce the size of APK in Android

What exactly is an APK file? The full form of APK is Android Package Kit. It is the Android operating system's application file format. We use Android Studio to generate APK...

7 minutes read.

How to Generate QRCode in Android?

Many apps use QR codes to show data in a way that is machine-readable. Data is represented using these codes in a secure manner such that only computers, not humans,...

4 minutes read.

Android TextView

Widgets are user interface (UI) elements that help users to interact with Android applications. It is one of many equipments that can be used to improvise the user interface of...

4 minutes read.

Android Project Folder Structure

JetBrains community developed Android Studio, the official IDE (Integrated Development Environment) for Android app development and is freely distributed by Google. After the complete Android Architecture setup, we can construct an...

4 minutes read.

Android Time picker example

How to pick Time from the user in android? Write an android example to pick Time from the user and display the date to the user. Android provides controls for the user...

3 minutes read.

Android Studio's Layout Editor

The Layout Editor allows you to efficiently create layouts by dragging UI elements from the Palette into the visual design editor instead of manually creating the layout XML file by...

8 minutes read.

Android Activity

What is an Activity? Android Activity is a screen in the user interface of an Android application. In this way, Android activity is very similar to the desktop application window. An...

4 minutes read.

Android EditText

In Android, EditText is a UI widget utilized to allow the user to input or change the text. While using the EditTextwidget in your Android application, you need to use...

4 minutes read.

Creating a Calendar View App in Android

This article demonstrates how to make an Android application that uses CalendarView to display the Calendar. It also provides the option to pick the current date and view the date....

3 minutes read.

Top Programming Languages for Android Development

For mobile apps, there are so many programming languages. You would need to spend days simply researching if you had to pick one from a list of 30 coding languages...

8 minutes read.

Android Styles and Themes

Android styles allow you to design the appearance (for example, colors, size, and fonts) of Android UI components from XML resource files. With this method, you only need to set...

5 minutes read.

Android Broadcast Receivers

Android applications can send or receive broadcast messages from the Android operating system and other Androidapplications, like the publish-subscribe design pattern. When an event of interest happens,these broadcasts are sent. For...

4 minutes read.

Android ListView

A kind of AdapterView that displays a vertical list of scrollable views, each of which is laid out below each other is called ListView. Using adapters, items are inserted into...

4 minutes read.

Top 7 Android App Development Books

Do you want to create Android apps but don't know where to start? One should first be familiar with the basics of Android before we discuss these books. With the...

5 minutes read.