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

Cách tạo Dialog tùy chỉnh (Custom Dialog) trên Android?

Giới thiệu

Hướng dẫn tạo hộp thoại (Dialog) tùy chỉnh hoàn toàn giao diện bằng layout XML riêng, cho phép nhập liệu, hiển thị thông tin phức tạp thay vì AlertDialog đơn giản.

Các bước thực hiện

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

Khởi tạo project Android Studio.

Bước 2: Giao diện chính (res/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="match_parent"
        android:layout_height="wrap_content"
        android:text="Tin nhắn tùy chỉnh của tôi"
        android:textSize="22sp"
        android:textAlignment="center"
        android:layout_marginTop="30dp"
        android:id="@+id/myCustommessage"/>
    <Button
        android:layout_width="140dp"
        android:layout_height="80dp"
        android:layout_centerInParent="true"
        android:text="Hiện tin nhắn"
        android:backgroundTint="@color/colorPrimary"
        android:textSize="20dp"
        android:textColor="#ffffff"
        android:onClick="btn_showMessage" />
</RelativeLayout>

Bước 3: Tạo layout Dialog tùy chỉnh

Trong Project: res → right-click layout → New → Layout resource file
Tên file: custom_dialog.xml, Root element: LinearLayout

Bước 4: Nội dung custom_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="15dp">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Nhập tin nhắn của bạn"
        android:textSize="22sp"
        android:textAlignment="center" />
    <EditText
        android:id="@+id/txt_input"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:hint="Nhập tin nhắn"
        android:textSize="20sp" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp">
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:backgroundTint="@color/colorPrimary"
            android:text="Hủy"
            android:textColor="#ffffff"
            android:textSize="18sp"
            android:layout_weight="1"
            android:id="@+id/btn_cancel"/>
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:backgroundTint="@color/colorPrimary"
            android:text="Đồng ý"
            android:textColor="#ffffff"
            android:textSize="18sp"
            android:layout_weight="1"
            android:id="@+id/btn_okay"/>
    </LinearLayout>
</LinearLayout>

Bước 5: Logic hiển thị Dialog (src/MainActivity.java)

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

public class MainActivity extends AppCompatActivity {
    TextView myCustomMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myCustomMessage = findViewById(R.id.myCustommessage);
    }

    public void btn_showMessage(View view) {
        AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
        View mView = getLayoutInflater().inflate(R.layout.custom_dialog, null);

        final EditText txtInput = mView.findViewById(R.id.txt_input);
        Button btnCancel = mView.findViewById(R.id.btn_cancel);
        Button btnOkay = mView.findViewById(R.id.btn_okay);

        alert.setView(mView);
        final AlertDialog alertDialog = alert.create();
        alertDialog.setCanceledOnTouchOutside(false); // Không tắt khi chạm ngoài

        btnCancel.setOnClickListener(v -> alertDialog.dismiss());

        btnOkay.setOnClickListener(v -> {
            myCustomMessage.setText(txtInput.getText().toString());
            alertDialog.dismiss();
        });

        alertDialog.show();
    }
}

Bước 6: 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>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. Nhấn "Hiện tin nhắn" → Dialog hiện ra → nhập text → nhấn "Đồng ý" → TextView chính cập nhật nội dung.

Cách tạo Dialog tùy chỉnh (Custom Dialog) trên Android?

Cách tạo Dialog tùy chỉnh (Custom Dialog) trên Android?

Mở rộng: DialogFragment (Khuyên dùng cho app phức tạp)

DialogFragment quản lý vòng đời tốt hơn, tự xử lý rotation, back stack:

public class MyCustomDialogFragment extends DialogFragment {
    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.custom_dialog, null);
        // ... setup view ...
        builder.setView(view);
        return builder.create();
    }
}

// Hiển thị:
new MyCustomDialogFragment().show(getSupportFragmentManager(), "custom_dialog");

Best Practices

  • Dùng DialogFragment thay vì AlertDialog trực tiếp trong Activity
  • Set setCanceledOnTouchOutside(false) cho form quan trọng
  • Validate input trước khi dismiss
  • Truyền data qua Interface/Listener hoặc ViewModel (LiveData/Flow)
  • Theme dialog: R.style.Theme_AppCompat_Light_Dialog_Alert hoặc custom