ภาพรวม
ตัวอย่างนี้แสดงวิธีการสร้างและแสดง Alert Dialog ในแอปพลิเคชัน Android โดยใช้ AlertDialog.Builder ซึ่งเป็นวิธีมาตรฐานสำหรับการแสดงกล่องโต้ตอบที่ต้องการการยืนยันจากผู้ใช้
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
เปิด Android Studio ไปที่ File → New Project และกรอกข้อมูลที่จำเป็นเพื่อสร้างโปรเจกต์ใหม่
ขั้นตอนที่ 2: จัดทำ 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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="กดปุ่ม Back เพื่อทดสอบ"
android:textStyle="bold"
android:textSize="24sp"
android:layout_centerInParent="true" />
</RelativeLayout>
ขั้นตอนที่ 3: เขียนโค้ดหลัก (MainActivity.java)
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("คุณต้องการออกจากแอปหรือไม่?");
builder.setTitle("แจ้งเตือน!");
builder.setCancelable(false);
builder.setPositiveButton("ใช่", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.setNegativeButton("ไม่", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.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>
การทดสอบ
รันแอปพลิเคชันบนอุปกรณ์จริงหรือ Emulator จากนั้นกดปุ่ม Back บนอุปกรณ์ จะเห็น Alert Dialog ปรากฏขึ้นพร้อมตัวเลือก "ใช่" และ "ไม่"