How To Create a ListView In Android Studio – Android ListView Tutorial

ListView is a view group that displays a list of scrollable items. 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.

Step 1 :Open activity_main.xml and write the code below to make ListView in the design part.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.bytelogs.listviewexample.MainActivity">


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

 

Step 2:Create a values.xml file by right clicking on values for string array data and name it months.xml
 values -> new -> values resource file 
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="months">
        <item>January</item>
        <item>February</item>
        <item>March</item>
        <item>April</item>
        <item>May</item>
        <item>June</item>
        <item>July</item>
        <item>August</item>
        <item>September</item>
        <item>October</item>
        <item>November</item>
        <item>December</item>
    </string-array>
</resources>

 

Step 3: Add below string array.This is the data that is be presented on the listview.
Step 4: Add this code below in MainActivity.
package com.bytelogs.listviewexample;

import android.support.v7.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 {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ListView listView = (ListView)findViewById(R.id.monthlistView);//declare listView
        ArrayAdapter monthsarray = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,R.array.months);//create arrayadapter
        listView.setAdapter(monthsarray);//setting arrayadapter to listView
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String value = (String)adapterView.getItemAtPosition(i);           //make nitemClick listener
                Toast.makeText(getBaseContext(), value,Toast.LENGTH_LONG).show();  //on item clicked make toast meassage
            }
        });
    }
}