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

Cách tạo Dialog với tùy chọn Neutral (Trung lập) trên Android

Giới thiệu về Dialog 3 nút: Positive - Neutral - Negative

Android AlertDialog.Builder hỗ trợ 3 loại nút:

  • Positive (Đồng ý): setPositiveButton - hành động chính (Yes, OK, Accept)
  • Negative (Từ chối): setNegativeButton - hành động phụ (No, Cancel, Decline)
  • Neutral (Trung lập): setNeutralButton - hành động trung gian (Later, Remind me, Maybe)

Ví dụ minh họa

Bước 1: Tạo project

Android Studio → File → New Project.

Bước 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:id="@+id/parent"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:gravity="center"
    android:orientation="vertical">
    <Button
        android:id="@+id/customDialog"
        android:text="Custom Dialog"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

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

package com.example.andy.myapplication;

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

public class MainActivity extends AppCompatActivity {

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.customDialog).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                
                builder.setTitle("Alert Dialog");
                builder.setMessage("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s");
                
                // Nút Positive (Yes)
                builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(MainActivity.this, "You have clicked Yes", Toast.LENGTH_LONG).show();
                    }
                });
                
                // Nút Negative (No)
                builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(MainActivity.this, "You have clicked No", Toast.LENGTH_LONG).show();
                    }
                });
                
                // Nút Neutral (Cancel)
                builder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(MainActivity.this, "You have clicked Neutral", Toast.LENGTH_LONG).show();
                    }
                });
                
                AlertDialog alertDialog = builder.create();
                alertDialog.show();
            }
        });
    }
}

Kết quả

Dialog hiển thị 3 nút: Yes | Cancel | No (thứ tự: Positive - Neutral - Negative)

Click từng nút hiển thị Toast tương ứng.

Thứ tự hiển thị nút (Material Design)

Vị trí Button Màu mặc định Use case
Trái (hoặc dưới) Negative Text color Hủy, Từ chối, Đóng
Giữa Neutral Text color Sau, Nhắc sau, Bỏ qua
Phải (hoặc trên) Positive Accent color Đồng ý, OK, Lưu, Xác nhận

Custom Button Order (API 23+)

// Thay đổi thứ tự nút (chỉ API 23+)
alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "No", listener);
alertDialog.setButton(DialogInterface.BUTTON_NEUTRAL, "Maybe", listener);
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Yes", listener);

DialogFragment với 3 nút (Hiện đại)

public class ThreeButtonDialogFragment extends DialogFragment {
    public interface Listener {
        void onPositiveClick();
        void onNegativeClick();
        void onNeutralClick();
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("Confirmation")
               .setMessage("Are you sure?")
               .setPositiveButton("Yes", (d, w) -> listener.onPositiveClick())
               .setNegativeButton("No", (d, w) -> listener.onNegativeClick())
               .setNeutralButton("Later", (d, w) -> listener.onNeutralClick());
        return builder.create();
    }
}

Tùy chỉnh giao diện nút

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

// Sau show() mới truy cập được button
Button positiveBtn = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
Button negativeBtn = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
Button neutralBtn = dialog.getButton(DialogInterface.BUTTON_NEUTRAL);

// Custom màu, font, size
positiveBtn.setTextColor(Color.WHITE);
positiveBtn.setBackgroundColor(Color.BLUE);
positiveBtn.setAllCaps(false); // Tắt ALL CAPS mặc định

Lưu ý

  • Neutral button thường dùng cho "Remind me later", "Skip for now"
  • Không bắt buộc phải có cả 3 nút
  • Click ngoài dialog/bấm back mặc định dismiss (setCanceledOnTouchOutside)
  • Dùng DialogFragment để xử lý rotation tự động