Android – ListView

Listview may be a collection of things pulled from arraylist, list or any databases. Most uses of listview may be a collection of things in vertical format, We will scroll up/down and click on on any item.
This example demonstrate about the way to make a ListView in android studio.

Step 1

Create a New Project and fill all required details to make a replacement project.
listview

Step 2

Now add the below code into res->layout->activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android = "http://schemas.android.com/apk/res/android"
    xmlns:tools = "http://schemas.android.com/tools"
    android:layout_width = "match_parent"
    android:layout_height = "match_parent">
    <LinearLayout
        android:layout_width = "match_parent"
        android:layout_height = "match_parent"
        android:orientation = "vertical">
        <ListView
            android:id = "@+id/list"
            android:layout_width = "wrap_content"
            android:layout_height = "wrap_content"/>
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

Step 3

Now go to MainActivity.java class and copy & paste below java code. This code belong to onCreate method.
package com.android.listview;

import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ListView list = findViewById(R.id.list);
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("Android");
        arrayList.add("Google");
        arrayList.add("Bing");
        arrayList.add("Facebook");
        arrayList.add("Youtube");
        arrayList.add("Instagram");
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, arrayList);
        list.setAdapter(arrayAdapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String clickedItem=(String) list.getItemAtPosition(position);
                Toast.makeText(MainActivity.this,clickedItem,Toast.LENGTH_LONG).show();
            }
        });
    }
}

Step 4

Now connect your Android Mobile device with Android Studio for checking output of application. Open one of your project’s activity files and click Run icon from the toolbar.
listview