android training

How to use Listview in android studio step by step? android tutorial

In this Android tutorial, we will learn how to use listview in the android studio? We will build an app. This app will contain a list of countries and when someone clicks on any country, a Toast message will appear on the screen. So create you blank project.

Useful android tutorials

Edit MainActivity.xml file

Add listview in MainActivity.xml and give as id to it. We need only Listview and nothing else.

    app:layout_constraintHorizontal_bias="0.0" />

Edit Strings.xml

Now open Strings.xml. In this file we will add list of countries. We are using <string-array name=”array”> </string-array> tag and <item> tag to enter the full list of countries. See the String.xml file code in the following block.

    <string name="app_name">My Application</string>

    <string-array name="array">



        <item> Egypt</item>



It’s  obvious that in this file we will add java code. This java code is not complex. It’s easy and simple.

package com.exampel.gaurav.myapplication;

import android.os.Bundle;
import android.view.View;
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 listView;
String[] array;
ArrayAdapter&amp;amp;amp;lt;String&amp;amp;amp;gt; arrayAdapter;
protected void onCreate(Bundle savedInstanceState) {
listView = (ListView)findViewById(;

array = getResources().getStringArray(R.array.array);
arrayAdapter = new ArrayAdapter&amp;amp;amp;lt;String&amp;amp;amp;gt;(this,android.R.layout.simple_list_item_1,array);

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView&amp;amp;amp;lt;?&amp;amp;amp;gt; parent, View view, int position, long id) {

Toast.makeText(getApplicationContext(),"you clicked on :" +arrayAdapter.getItem(position),Toast.LENGTH_LONG).show();




In this code, we made instances of Listview and Arrayadapter. To access the data from strings.xml , we made a array and access it by using getResources method and pass string array name in getStringArray(R.array.array). Then in Arrayadapter it takes 3 arguments. First is this. Second is xml layout style. Here you can make your own xml also but you can use builtin file also. This file will decide how the Listview will look like. In this case we have used builtin file  android.R.layout.simple_list_item_1.  The last argument is array name which is array in this case. Now you can run your app. See the result in video.

Leave a Reply

Your email address will not be published. Required fields are marked *