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

Cách tạo Dialog Box không có tiêu đề (title) trên Android bằng Kotlin

Giới thiệu

Ví dụ minh họa cách tạo AlertDialog không hiển thị tiêu đề (title) trên Android bằng Kotlin. Mặc định AlertDialog.Builder không có title nếu không gọi setTitle().

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

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

Android Studio > File > New Project.

Bước 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:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="70dp"
        android:background="#008080"
        android:padding="5dp"
        android:text="TutorialsPoint"
        android:textColor="#fff"
        android:textSize="24sp"
        android:textStyle="bold" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Alert Dialog không có tiêu đề"
        android:textAlignment="center"
        android:textColor="@android:color/holo_orange_dark"
        android:textSize="24sp"
        android:textStyle="bold" />

</RelativeLayout>

Bước 3: MainActivity.kt - AlertDialog không title

import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"

        val builder = AlertDialog.Builder(this)
        // KHÔNG gọi builder.setTitle("...")

        builder.setMessage("Bạn có muốn đóng dialog này không?")
        builder.setPositiveButton("Có") { dialog, _ ->
            dialog.dismiss()
            Toast.makeText(applicationContext, "Dialog đã được đóng", Toast.LENGTH_LONG).show()
        }
        builder.setNegativeButton("Không") { _, _ -> }

        val alertDialog = builder.create()
        alertDialog.show()
    }
}

Bước 4: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.notitledialog">

    <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

Chạy app, Dialog hiện ra ngay khi Activity tạo. Dialog chỉ có nội dung thông báo và 2 nút "Có"/"Không", không có thanh tiêu đề (title bar).

Tùy chỉnh Dialog nâng cao

1. Custom Layout hoàn toàn (Không dùng AlertDialog.Builder message)

val inflater = layoutInflater
val dialogView = inflater.inflate(R.layout.custom_dialog, null)
val dialog = AlertDialog.Builder(this)
    .setView(dialogView)
    .create()
// Tìm view trong dialogView: dialogView.findViewById(R.id.tvMessage).text = "..."
dialog.show()

2. DialogFragment (Khuyến nghị cho cycle life phức tạp)

class MyDialogFragment : DialogFragment() {
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return AlertDialog.Builder(requireContext())
            .setMessage("Nội dung")
            .setPositiveButton("OK") { _, _ -> }
            .create()
    }
}
// Hiển thị: MyDialogFragment().show(supportFragmentManager, "MyDialog")

3. MaterialAlertDialogBuilder (Material Components)

implementation "com.google.android.material:material:1.10.0"

MaterialAlertDialogBuilder(this)
    .setTitle("Tiêu đề") // Có title
    .setMessage("Nội dung")
    .setPositiveButton("Đồng ý") { _, _ -> }
    .setNegativeButton("Hủy") { _, _ -> }
    .show()

4. Ẩn title nhưng vẫn có icon/custom view ở top

val dialog = AlertDialog.Builder(this).create()
dialog.setCustomTitle(customTitleView) // View tùy chỉnh thay title mặc định
// Hoặc
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) // Phải gọi trước create()/show()
dialog.setContentView(R.layout.custom_dialog_layout)

Tóm tắt

  • Không gọi setTitle() = Không có title (cách đơn giản nhất).
  • Dùng requestWindowFeature(Window.FEATURE_NO_TITLE) trước create() nếu dùng setContentView hoặc muốn chắc chắn không có title bar.
  • Ưu tiên DialogFragment + MaterialAlertDialogBuilder cho app hiện đại.