How to create ListView using Adapter in Android Tutorial

In this tutorial, we’re explaining the way to create ListView in Android Application.

What is Android ListView?

Don't Miss

Android ListView is a view which teams a number of objects and show them in vertical scrollable list. The list items are automatically inserted to the list utilizing an Adapter that pulls content material from a supply reminiscent of an array or database. It’s one of many primary and most used UI components of android. The most common usages include displaying information within the type of a vertical scrolling list.

Note also You can get reference from below Tutorial –

Using an Adapter

An adapter really bridges between UI components and the info supply that fill data into UI Component. Adapter holds the info and ship the info to adapter view, the view can take the info from adapter view and shows the data on completely different views like as spinner, list view, grid view and so forth. The adapter pulls the items out of a data source, an array for example, after which converts every item right into a view which it then inserts into the listView.

The ListView and GridView are subclasses of AdapterView and they are often populated by binding them to an Adapter, which retrieves data from an exterior supply and creates a View that represents every data entry. The common adapters are ArrayAdapter, BaseAdapter, CursorAdapter, SimpleCursorAdapter, SpinnerAdapter and WrapperListAdapter.

Add ListView in Layout File

To display list item, we need to add ListView in the main Activity file

<?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"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_width="match_parent"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_height="wrap_content" >
    </ListView>


</androidx.constraintlayout.widget.ConstraintLayout>

Add TextView

To display text in the list, we need to create a file activity_list_view.xml file. Add the following code:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/label"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dip"
    android:textSize="16dip"
    android:textStyle="bold" >
</TextView>

Create a Sting Array

We need to add list item in the array. We will display data in the listview from Array item.

String[] countryArray = {"Afghanistan","Bangladesh","Canada","Denmark",
            "Germany","Iceland","Egypt","Egypt"};

ArrayAdapter

You can use this adapter when your information source is an array. By default, ArrayAdapter creates a view for every array item by calling toString() on every item and putting the contents in a TextView. Consider you have got an array of strings you need to show in a ListView, initialize a new ArrayAdapter using a constructor to specify the layout for each string and the string array

ArrayAdapter adapter = new ArrayAdapter<String>(this,
                R.layout.activity_list_item, countryArray);

Here are arguments for this constructor −

  • First argument this is the application context. Most of the case, keep it this.
  • Second argument will be layout defined in XML file and having TextView for each string in the array.
  • Final argument is an array of strings which will be populated in the text view.

Once you have array adapter created, then simply call setAdapter() on your ListView object as follows

ListView listView = (ListView) findViewById(R.id.list);
        listView.setAdapter(adapter);

Handling Android ListView Clicks

The onListItemClick() methodology is used to process the clicks on android ListView item. This methodology receives four parameters:

  1. ListView : The ListView containing the item views
  2. View : The particular item view that was chosen
  3. Position : The place of the chosen item within the array. Remember that the array is zero listed, so the primary item within the array is at position 0
  4. Id : The id of the chosen item. Not of significance for our tutorial however is essential when utilizing data retrieved from a database as you should utilize the id (which is the id of the row containing the item within the database) to retrieve the item from the database
        // listening to single list item on click
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                // selected item
                String team = ((TextView) view).getText().toString();
                Toast.makeText(MainActivity.this, team, LENGTH_SHORT).show();

            }
        });

Full Code

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.TextView;
import android.widget.Toast;

import static android.widget.Toast.LENGTH_SHORT;

public class MainActivity extends AppCompatActivity {
    String[] countryArray = {"Afghanistan","Bangladesh","Canada","Denmark",
            "Germany","Iceland","Egypt","Egypt"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ArrayAdapter adapter = new ArrayAdapter<String>(this,
                R.layout.activity_list_item, countryArray);

        ListView listView = (ListView) findViewById(R.id.list);
        listView.setAdapter(adapter);

        // listening to single list item on click
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                // selected item
                String team = ((TextView) view).getText().toString();
                Toast.makeText(MainActivity.this, team, LENGTH_SHORT).show();

            }
        });
    }

LEAVE A REPLY

Please enter your comment!
Please enter your name here

564FansLike

Recent Posts

Concept of Session in Laravel Tutorial

Sessions are used to store details about the user throughout the requests. Laravel supplies various drivers like file, cookie, apc, array, Memcached, Redis, and database to handle session data. By default, file driver is used as a result of it's light-weight....

Laravel Url Generation Tutorial

Our web application revolves around routes and URLs. After all, they're what direct our users to our pages. At the end of the day, serving pages is what any web application should do. Our users may...

Concept of Laravel Views Tutorial

In MVC framework, the letter "V" stands for Views. It separates the application logic and presentation logic. Views are saved in resources/views listing. Generally, the view contains the HTML which might be served by the application.

Related Articles

Concept of Session in Laravel Tutorial

Sessions are used to store details about the user throughout the requests. Laravel supplies various drivers like file, cookie, apc, array, Memcached, Redis, and database to handle session data. By default, file driver is used as a result of it's light-weight....

Laravel Url Generation Tutorial

Our web application revolves around routes and URLs. After all, they're what direct our users to our pages. At the end of the day, serving pages is what any web application should do. Our users may...

Concept of Laravel Views Tutorial

In MVC framework, the letter "V" stands for Views. It separates the application logic and presentation logic. Views are saved in resources/views listing. Generally, the view contains the HTML which might be served by the application.
WP2Social Auto Publish Powered By : XYZScripts.com