In the Android operating system, ListView is a graphical element that lets you display a list of items in a scrollable list. For example, you might use ListView to show a list of contacts or a list of songs in a music app.
To create a ListView, developers must create an Adapter class that tells the ListView what to display. The Adapter provides the data shown in the list and handles user interactions like clicking on an item.
The ListView is very customizable, so developers can create a unique look and feel for their app. The ListView has features like scrolling, multi-selection, and the ability to use custom views.
While newer alternatives are available, like RecyclerView, ListView is still widely used in older Android apps and is an essential part of Android’s user interface toolkit.
In our previous tutorial, you learned about Android WebView. Today, we will cover a simple Android ListView tutorial that will help you 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, 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.
Also Read: Android 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 given it an id of myList.
Now, we will work with the Java file of this main activity.
We first import AdapterView, ArrayAdapter, ListView, and Toast in this file.
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 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); } }
In the third line of the 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!
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.
Implementing Long Click
If you want to perform some operations when the user presses an item for as long as we do in Gmail App to delete emails.
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
First, 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 defined a View named mView and linked it to our Item’s Layout file.
After that, we linked the variables mView and mButton with their views in the Layout file.
After that, we 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.
In the onCreate method, use this code to link our ListView with our custom ArrayAdapter.
MyArrayAdapter mAdapter = new MyArrayAdapter(this,mListArray); mListView.setAdapter(mAdapter);
Now our ListView Android application looks like this.
Also Read: 15 Best Free International Calling Apps [2020].
Final Thoughts
This simple tutorial teaches you 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 you can also use listView if you don’t have an extensive dataset.
I hope you enjoyed this tutorial; let’s catch up on the next one. :)
Avid Android developer with 2 years of experience. Reading books and stay updated with the latest development trends is all I do :)