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

Cách sử dụng Singleton AlertDialog trong Android

Quản lý AlertDialog tập trung với Singleton

Ví dụ này demo việc đóng gói AlertDialog vào lớp Singleton, cho phép hiển thị dialog xác nhận từ bất kỳ đâu trong ứng dụng chỉ với một dòng code.

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

Android Studio → File → New Project.

Bước 2: Giao diện (activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    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"
    android:orientation="vertical">

    <Button
        android:id="@+id/show"
        android:text="Alert Dialog từ Singleton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

Bước 3: MainActivity.java

package com.example.alertdialogsingleton;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    Button btnShow;
    SingleTonExample singletonExample;

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

        btnShow = findViewById(R.id.show);
        singletonExample = SingleTonExample.getInstance();
        singletonExample.init(getApplicationContext());

        btnShow.setOnClickListener(v -> 
            singletonExample.showAlertDialog(MainActivity.this)
        );
    }
}

Bước 4: SingleTonExample.java

package com.example.alertdialogsingleton;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.widget.Toast;

public class SingleTonExample {
    private Context appContext;
    private static final SingleTonExample ourInstance = new SingleTonExample();

    public static synchronized SingleTonExample getInstance() {
        return ourInstance;
    }

    private SingleTonExample() { }

    public void init(Context context) {
        if (appContext == null) {
            this.appContext = context;
        }
    }

    private Context getContext() {
        return appContext;
    }

    public static Context get() {
        return getInstance().getContext();
    }

    public void showAlertDialog(final MainActivity activity) {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setMessage("Bạn có chắc chắn muốn thực hiện hành động này?");
        
        builder.setPositiveButton("Có", (dialog, which) -> 
            Toast.makeText(activity, "Bạn đã nhấn Có", Toast.LENGTH_LONG).show()
        );
        
        builder.setNegativeButton("Không", (dialog, which) -> 
            activity.finish()
        );

        AlertDialog dialog = builder.create();
        dialog.show();
    }
}

Chạy ứng dụng

Nhấn nút → hiển thị AlertDialog với hai lựa chọn "Có" và "Không". Chọn "Có" hiện Toast, chọn "Không" đóng Activity.

Mở rộng: Singleton AlertDialog linh hoạt hơn

public class AlertDialogSingleton {
    private static AlertDialogSingleton instance;
    private Context context;

    private AlertDialogSingleton(Context context) {
        this.context = context.getApplicationContext();
    }

    public static synchronized AlertDialogSingleton getInstance(Context context) {
        if (instance == null) {
            instance = new AlertDialogSingleton(context);
        }
        return instance;
    }

    public void showConfirm(String title, String message, 
                           DialogInterface.OnClickListener positiveAction,
                           DialogInterface.OnClickListener negativeAction) {
        new AlertDialog.Builder(context)
            .setTitle(title)
            .setMessage(message)
            .setPositiveButton("Đồng ý", positiveAction)
            .setNegativeButton("Hủy", negativeAction)
            .show();
    }
}

// Cách dùng:
AlertDialogSingleton.getInstance(this)
    .showConfirm("Xác nhận", "Xóa mục này?", 
        (d, w) -> deleteItem(), 
        (d, w) -> d.dismiss());

Ưu điểm

  • Code DRY (Don't Repeat Yourself) - không lặp lại boilerplate AlertDialog
  • Dễ dàng thay đổi giao diện dialog toàn ứng dụng (theme, style)
  • Quản lý vòng đời dialog tập trung