Android ListView Tutorial With Example Project

0
55

In our previous tutorial, you learned about Android WebView. Today, we will see cover a simple Android ListView tutorial that will help you to understand the basic concept of ListView.

So, if you are beginning to learn Android application development and want to learn how to implement ListView in your application, then you have landed on the right page.

What is ListView in Android app development?

ListView is a view that groups several elements in a scrollable list. The list items are automatically added from a data source such as an array or database using an Adapter.

Android ListView Tutorial Content Index

  1. Creating a simple ListView
  2. Implementing long click on ListView items
  3. Customizing ListView

Also ReadAndroid app to execute code in 23+ programming languages.

Creating a Simple ListView

Create an empty Android app development project in Android Studio and place this code in the main activity layout 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"
    android:background="#FFFFFF"
    tools:context=".MainActivity">

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

Here we have added a ListView component and gave it an id of myList.

Now, we will work with the Java file of this main activity.

In this file, we first import AdapterView, ArrayAdapter, ListView, and Toast.

package com.example.gbfirst;

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;

public class MainActivity extends AppCompatActivity {
    ListView mListView;
    String[] mListArray = {"C","C++","JAVA","PYTHON","JAVASCRIPT","GOLANG","PHP","RUBY"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
    }
}

Then we have defined two variables, mListView and mListArray. mListView variable is for our list view, and mListArray is the data array.

Now we here is the main code to implement ListView in an Android application.

package com.example.gbfirst;

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;

public class MainActivity extends AppCompatActivity {
    ListView mListView;
    String[] mListArray = {"C","C++","JAVA","PYTHON","JAVASCRIPT","GOLANG","PHP","RUBY"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mListView = (ListView) findViewById(R.id.myList);
        ArrayAdapter<String> mAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,mListArray);
        mListView.setAdapter(mAdapter);
    
    }
}

Here you can see in the third line of onCreate method we linked the mListView variable with our ListView in the layout file.

Then we defined an ArrayAdapter and linked it to mListArray.

And at last, we linked our mAdapter to mListView using the setAdapter method.

See we have a working list view, Yay!

android listview tutorial

But hey the items are not clickable yet, so let’s make them clickable.

In the onCreate method, enter this code.

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this,"You clicked "+mListArray[position],Toast.LENGTH_LONG).show();
            }
});

Now you will see a message like this when you click an item.

android listview

Also ReadFrom Scratch to Best Tool: Everything About Developing Chatbots for Your Business.

Implementing Long Click

If you want to perform some operations when the user presses an item for long as we do in Gmail App to delete mails.

Then you can use this code for that.

mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
     @Override
     public boolean onItemLongClick(AdapterView<?> arg0, View arg1,int pos, long id) {
         Toast.makeText(MainActivity.this,"You long clicked "+mListArray[pos],Toast.LENGTH_LONG).show();
         return true;
     }
 });

Customizing our ListView

Now that we have created a simple ListView, let’s customize it.

So for that first, we will create a new layout in the res/layout folder for our list item.

We are naming it myitem.xml

Here is a code for that

<?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="wrap_content">

    <TextView
        android:id="@+id/mTextView"
        android:layout_width="0dp"
        android:layout_margin="20dp"
        android:layout_height="wrap_content"
        android:text="TextView"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/mButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CLICK ME"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/mTextView" />
</androidx.constraintlayout.widget.ConstraintLayout>

Now in our Activity Java file, we will create our ArrayAdapter

Firs define a class named MyArrayAdapter that extends ArrayAdapter<String>

package com.example.gbfirst;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    ListView mListView;
    String[] mListArray = {"C","C++","JAVA","PYTHON","JAVASCRIPT","GOLANG","PHP","RUBY"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mListView = (ListView) findViewById(R.id.myList);
       MyArrayAdapter mAdapter = new MyArrayAdapter(this,mListArray);
        mListView.setAdapter(mAdapter);

    }

    class MyArrayAdapter extends ArrayAdapter<String>{
    }
}


Now we will define an Array and a constructor inside this MyArrayAdapter class.

String[] mArray;
public MyArrayAdapter(@NonNull Context context, String[] mArray) {
    super(context, R.layout.myitem, mArray);
    this.mArray = mArray;
}

Now let’s implement a method for returning our Item’s View.

@NonNull
     @Override
     public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
         LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
         View mView = layoutInflater.inflate(R.layout.myitem,parent,false);
         Button mButton = (Button) mView.findViewById(R.id.mButton);
         TextView mTV = (TextView) mView.findViewById(R.id.mTextView);
         mTV.setText(mArray[position]);
         mButton.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 Toast.makeText(MainActivity.this,"You clicked "+mArray[position],Toast.LENGTH_LONG).show();
             }
         });
         return mView;
     }

Now let us understand this method’s statements one by one.

First, we have defined a LayoutInflater and assigned it a LayoutInflater service.

Then we have defined a View named mView and linked it to our Item’s Layout file.

After that, we have linked the variables mView and mButton with their views in the Layout file.

After that, we have assigned the value of Array at the current position to the text of mTV.

Next, we have to set an OnClickListener for the button so that whenever someone clicks this, a Toast is shown.

At last, we return the mView.

Now in the onCreate method, let us link our ListView with our custom ArrayAdapter using this piece of code.

MyArrayAdapter mAdapter = new MyArrayAdapter(this,mListArray);
mListView.setAdapter(mAdapter);

Now our ListView Android application looks like this.

click elements in listview

Also Read15 Best Free International Calling Apps [2020].

Final Thoughts

In this simple tutorial, you learn how to implement a ListView in an Android application. Now a little tip at the end, it is recommended to use RecyclerView nowadays in place of ListView because it is more efficient, but ListView can also be used if you don’t have a big dataset.

Hope you enjoyed this tutorial, now let’s catch up in the next one. :)