In this tutorial I am going to discuss about How to create ListView in android application ?

ListView is just a kind of AdapterView that is used to show the collection of items in a vertically-scrollable list. The list items are automatically inserted to the list using an Adapter that pulls content from a source such as an array or database query and converts each item result into a view that’s placed into the list.

As similar to GridView, ListView is also a ViewGroup . In ListView each items is positioned just below the last item . ListView is an implementation of android widget and by default it provides vertical scrolling between items. In ListView each items have an unique position. But for more modern,flexible and efficient implementation we use RecyclerView to show the data into vertical or horizontal scrolling list.

1. Create a New Project :

Create a new project in Android Studio from File ⇒ New Project and select Empty Activity from templates to implement ListView to your app .

2. Add ListView to your activity_main.xml or main layout

Add ListView to your main layout.

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

Now open res -> layout -> activity_main.xml  file and just implement the following xml code .

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

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

</LinearLayout>

3. Now open your MainActivity.java and add following code :

Now create an instance of ArrayAdapter and setAdapter( ) to ListView .

package com.technxtcodelabs;

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


public class MainActivity extends AppCompatActivity {
    private ListView mlistview;
    static final String[] FRUITS = new String[] { "Apple", "Avocado", "Banana",
            "Blueberry", "Coconut", "Durian", "Guava", "Kiwifruit",
            "Jackfruit", "Mango", "Olive", "Pear", "Sugar-apple" };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mlistview = (ListView) findViewById(R.id.lv);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,FRUITS);
        mlistview.setAdapter(adapter);

    }
}

You can also customize the view of ListView with adding an image to it and changing the text size, colour etc .

Now run the project/app to test ListView in android app through android device or any Emulator .

%d bloggers like this: