How to Use ListView in Android Beginner’s Tutorial

ListView is a commonly used interface element in Android for displaying data lists. Here is a simple example demonstrating how to use ListView in Android.

  1. Add a ListView element in the layout file.
<ListView
    android:id="@+id/list_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
  1. In the Activity, locate the ListView and set the adapter.
ListView listView = findViewById(R.id.list_view);

// 准备数据
String[] data = new String[]{"Item 1", "Item 2", "Item 3", "Item 4", "Item 5"};

// 创建适配器
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, data);

// 设置适配器
listView.setAdapter(adapter);
  1. You can add a click event listener to a ListView in order to respond to user click actions.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Toast.makeText(MainActivity.this, "Clicked item " + position, Toast.LENGTH_SHORT).show();
    }
});

In this way, when a user clicks on an item in the list, a Toast message will appear to indicate which item was clicked. This is a simple example of how to use a ListView, hope it helps you.

Leave a Reply 0

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


广告
Closing in 10 seconds
bannerAds