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

วิธีปิด Dialog เมื่อคลิกนอกพื้นที่ Dialog ใน Android

ภาพรวม

ตัวอย่างนี้สาธิตวิธีการทำให้ Dialog ปิดอัตโนมัติเมื่อผู้ใช้คลิกที่พื้นที่นอก Dialog โดยใช้เมธอด setCanceledOnTouchOutside(true)

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

สร้างโปรเจกต์ Android ใหม่ใน Android Studio

ขั้นตอนที่ 2: ออกแบบ Layout (res/layout/activity_main.xml)

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

    <TextView
        android:id="@+id/click"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:text="คลิกเพื่อเปิด Dialog"/>

</LinearLayout>

ขั้นตอนที่ 3: เขียนโค้ด MainActivity (src/MainActivity.java)

import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    TextView text;

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

        text = findViewById(R.id.click);
        text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAlertBox();
            }
        });
    }

    private void showAlertBox() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
        alertDialog.setTitle("Dialog แจ้งเตือน");
        alertDialog.setMessage("ต้องการปิด Dialog นี้หรือไม่? คลิกนอกพื้นที่เพื่อปิด");
        
        alertDialog.setPositiveButton("ใช่", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "กดปุ่ม ใช่", Toast.LENGTH_LONG).show();
            }
        });
        
        alertDialog.setNegativeButton("ไม่", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // ไม่ทำอะไร - Dialog จะปิดเอง
            }
        });

        AlertDialog alert = alertDialog.create();
        
        // 🔑 จุดสำคัญ: ทำให้ปิดได้เมื่อคลิกนอกพื้นที่
        alert.setCanceledOnTouchOutside(true);
        
        // ตั้งค่าเพิ่มเติม
        alert.setCancelable(true); // ปิดได้ด้วยปุ่ม Back
        
        alert.show();
    }
}

ขั้นตอนที่ 4: 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>

ความแตกต่างระหว่าง setCancelable และ setCanceledOnTouchOutside

Methodพฤติกรรม
setCancelable(true)ปิด Dialog ได้ด้วยปุ่ม Back และ (ถ้า true) คลิกนอกพื้นที่
setCanceledOnTouchOutside(true)ปิด Dialog ได้เฉพาะเมื่อคลิกนอกพื้นที่ (ไม่รวมปุ่ม Back)

หมายเหตุ: หาก setCancelable(false) แล้ว setCanceledOnTouchOutside(true) จะไม่ทำงาน ต้องตั้งค่าทั้งคู่เป็น true

การป้องกันการปิด Dialog (Force User Action)

AlertDialog alert = alertDialog.create();
alert.setCancelable(false); // ปิดไม่ได้ด้วย Back
alert.setCanceledOnTouchOutside(false); // ปิดไม่ได้ด้วยการคลิกนอกพื้นที่
// ผู้ใช้ต้องกดปุ่ม Positive/Negative เท่านั้น

การทดสอบ

รันแอป กด "คลิกเพื่อเปิด Dialog" → คลิกที่พื้นที่มืดนอก Dialog → Dialog จะปิดอัตโนมัติ

วิธีปิด Dialog เมื่อคลิกนอกพื้นที่ Dialog ใน Android วิธีปิด Dialog เมื่อคลิกนอกพื้นที่ Dialog ใน Android