Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách dùng ArrayAdapter tạo ListView đơn giản trong Android

Giới thiệu

Bài viết này hướng dẫn sử dụng ArrayAdapter để hiển thị danh sách chuỗi đơn giản lên ListView. ArrayAdapter là adapter cơ bản nhất, phù hợp cho dữ liệu kiểu mảng hoặc List<String>.

Các bước thực hiện

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project và tạo dự án.

Bước 2: Layout chính (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/simpleListView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:divider="#000"
        android:dividerHeight="2dp" />

</RelativeLayout>

Bước 3: Layout item tùy chỉnh (res/layout/activity_array.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:padding="20dp"
        android:textColor="#000" />

</LinearLayout>

Bước 4: Code logic (src/MainActivity.java)

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {
    ListView simpleList;
    String[] playersList = {"Ronaldo", "Messi", "Neymar", "Isco", "Hazard"};

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

        simpleList = findViewById(R.id.simpleListView);

        // ArrayAdapter(context, layout_item, id_textview, data)
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(
            this,
            R.layout.activity_array,
            R.id.textView,
            playersList
        );

        simpleList.setAdapter(arrayAdapter);
    }
}

Bước 5: Cấu hình AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. ListView hiển thị 5 tên cầu thủ, mỗi dòng là một TextView tùy chỉnh từ activity_array.xml.

Các constructor ArrayAdapter phổ biến

// 1. Dùng layout hệ thống (simple_list_item_1)
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, data);

// 2. Dù layout tùy chỉnh + ID TextView trong layout đó
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.custom_item, R.id.textView, data);

// 3. Dùng List<String> thay vì mảng
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, stringList);

Xử lý sự kiện click item

listView.setOnItemClickListener((parent, view, position, id) -> {
    String selected = playersList[position];
    Toast.makeText(this, "Đã chọn: " + selected, Toast.LENGTH_SHORT).show();
});

Lưu ý

  • ArrayAdapter chỉ phù hợp dữ liệu đơn giản (String, Object có toString())
  • Đối với dữ liệu phức tạp (hình ảnh, nhiều trường), hãy dùng BaseAdapter hoặc RecyclerView + Adapter hiện đại hơn
  • ListView đã lỗi thời, Google khuyến nghị dùng RecyclerView cho danh sách phức tạp