Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีแสดง ListView ใน AlertDialog บน Android

ภาพรวม

ตัวอย่างนี้สาธิตการสร้าง AlertDialog ที่มี ListView ภายใน เหมาะสำหรับเมนูเลือกตัวเลือกหลายรายการ เช่น เลือกประเทศ, เมนูตั้งค่า, หรือรายการข้อมูล

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

Android Studio → File → New Project → Empty Activity

ขั้นตอนที่ 2: จัดรูปแบบหน้าจอหลัก (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">

    <Button
        android:id="@+id/btnClick"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Click here to get ListView in Alert Dialog"
        android:textSize="12sp"
        android:textStyle="bold"
        android:onClick="openDialog"/>

</RelativeLayout>

ขั้นตอนที่ 3: สร้าง Layout สำหรับ Dialog (row.xml)

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

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_above="@id/button"/>

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="ALL COUNTRIES"/>

</RelativeLayout>

ขั้นตอนที่ 4: เขียนโค้ด MainActivity.java

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

public class MainActivity extends AppCompatActivity {

    private final String[] names = {"India", "Brazil", "Argentina", 
                                    "Portugal", "France", "England", "Italy"};
    private ArrayAdapter adapter;
    private ListView listView;

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

    public void openDialog(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        
        // Inflate custom layout สำหรับ Dialog
        View dialogView = getLayoutInflater().inflate(R.layout.row, null);
        
        listView = dialogView.findViewById(R.id.listView);
        
        // ใช้ ArrayAdapter พื้นฐาน
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, names);
        listView.setAdapter(adapter);
        
        builder.setView(dialogView);
        
        AlertDialog dialog = builder.create();
        dialog.show();
        
        // ตัวอย่าง: จัดการกดปุ่มใน Dialog
        dialogView.findViewById(R.id.button).setOnClickListener(view -> {
            Toast.makeText(this, "All countries selected", Toast.LENGTH_SHORT).show();
            dialog.dismiss();
        });
        
        // ตัวอย่าง: จัดการกด Item ใน ListView
        listView.setOnItemClickListener((parent, view, position, id) -> {
            Toast.makeText(this, "Selected: " + names[position], Toast.LENGTH_SHORT).show();
        });
    }
}

ขั้นตอนที่ 5: 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>
                
                
            </intent-filter>
        </activity>

    </application>
</manifest>

การทดสอบ

รันแอป → กดปุ่ม "Click here..." → จะแสดง Dialog พร้อม ListView → กดรายการหรือปุ่มด้านล่าง

วิธีแสดง ListView ใน AlertDialog บน Android วิธีแสดง ListView ใน AlertDialog บน Android

แนวทางปัจจุบัน (Material Design)

แนะนำให้ใช้ MaterialAlertDialogBuilder (จาก Material Components Library) และ RecyclerView แทน ListView:

// build.gradle
implementation 'com.google.android.material:material:1.6.0'

// ในโค้ด
new MaterialAlertDialogBuilder(this)
    .setTitle("Select Country")
    .setAdapter(adapter, (dialog, which) -> {
        // Handle click
    })
    .show();

เคล็ดลับ

  • ใช้ dialog.getWindow().setLayout(width, height) ควบคุมขนาด Dialog
  • สำหรับรายการเยอะ ใช้ RecyclerView ใน Dialog แทน ListView
  • เพิ่ม SearchView ใน Dialog สำหรับกรองข้อมูล