List in Android Studio using Java

Tiempo de lectura: 2 minutos

To create a list of items and display them on Android, follow these steps as shown in the example.

First, create an XML file to define the view with the list. To display a list, we will use the “ListView” element.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</RelativeLayout>

Next, create a class where we will create the adapter to customize, handle, and display the data in the list as desired.

package com.maria.listas;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;

class Adapter extends ArrayAdapter {

    public Adapter(Context context, List data) {
        super(context, 0, data);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        String item = getItem(position);

        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
        }

        TextView textView = convertView.findViewById(android.R.id.text1);
        textView.setText(item);

        return convertView;
   html
Copy code
    }
}

Then, in the main class or Activity, configure the ListView along with the adapter,

package com.maria.listas;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

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

        ListView listView = findViewById(R.id.listView);

        List dataList = new ArrayList<>();
        dataList.add("Elemento 1");
        dataList.add("Elemento 2");
        dataList.add("Elemento 3");

        ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, dataList);
        listView.setAdapter(adapter);
    }
}

Finally, I show the result of the list with three elements on a mobile view.

I hope this helps; have a great day!

Leave a Comment