Android List View

In Android, a ListView is a UI component that displays a list of items in a vertical scrollable view. It is commonly used to display a collection of data, such as contacts, messages, or images, and allows the user to interact with the data by scrolling, selecting, and clicking on items.

Here is an example of how to use a ListView in Android:

First, you need to define the layout for each item in the ListView. This is typically done using a layout XML file that defines the UI elements for each item, such as an ImageView and TextView:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:padding="8dp">

  <ImageView
      android:id="@+id/imageView"
      android:layout_width="50dp"
      android:layout_height="50dp"
      android:layout_alignParentStart="true"
      android:src="@drawable/image" />

  <TextView
      android:id="@+id/textView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignTop="@id/imageView"
      android:layout_toEndOf="@id/imageView"
      android:text="Item Text" />

</RelativeLayout>

Next, you need to create an array of data that you want to display in the ListView. This could be an array of strings, images, or custom objects:

String[] items = { "Item 1", "Item 2", "Item 3" };

Then, in your Java code, you need to get a reference to the ListView and create an adapter to bind the data to the layout:

ListView listView = findViewById(R.id.listView);
ArrayAdapter adapter = new ArrayAdapter<>(this,
        R.layout.list_item, R.id.textView, items);
listView.setAdapter(adapter);

In this code, we create an ArrayAdapter that binds the data to the layout defined in the list_item.xml file. We set the text for each item using the TextView with the ID textView, and we set the array of data using the items array.

Finally, you can handle user interactions with the ListView by setting an OnItemClickListener:

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  @Override
  public void onItemClick(AdapterView parent, View view, int position, long id) {
      String selectedItem = (String) parent.getItemAtPosition(position);
      Toast.makeText(getApplicationContext(), selectedItem, Toast.LENGTH_SHORT).show();
  }
});

In this code, we display a Toast message when the user clicks on an item in the ListView.

The ListView is a powerful and versatile UI component in Android that allows you to display and interact with collections of data in a scrollable view. It can be customized with different layouts, adapters, and listeners to fit the needs of your application. ListView is still widely used, but there are more advanced alternatives such as RecyclerView and ViewPager2.

Next Article ❯