Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

Kotlin으로 Android에서 제목 없는 AlertDialog 만드는 방법

이 글에서는 Kotlin을 사용하여 Android 앱에서 제목(title) 없이 대화 상자(Dialog Box)를 생성하는 방법을 단계별로 살펴봅니다. 일반적인 AlertDialog는 기본적으로 제목 영역을 포함하지만, 빌더에 제목을 설정하지 않고 메시지와 버튼만 구성하면 제목 없는 깔끔한 다이얼로그를 만들 수 있습니다.

1단계: 새 프로젝트 생성

Android Studio를 실행하고 File ⇒ New Project 메뉴로 이동한 후, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력하여 프로젝트를 만듭니다. 언어는 Kotlin을 선택하세요.

2단계: activity_main.xml 레이아웃 작성

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: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 without title"
        android:textAlignment="center"
        android:textColor="@android:color/holo_orange_dark"
        android:textSize="24sp"
        android:textStyle="bold" />
</RelativeLayout>

3단계: MainActivity.kt 작성

src/MainActivity.kt 파일에 아래 코드를 추가합니다. 핵심은 AlertDialog.Builder를 생성할 때 setTitle()을 호출하지 않고 setMessage()와 버튼 리스너만 구성하는 것입니다. 이렇게 하면 제목 영역 없이 메시지와 [예]/[아니요] 버튼만 표시되는 다이얼로그가 완성됩니다.

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)
        builder.setMessage("Do you want to close the alert dialog without title?")
        builder.setPositiveButton("Yes") { dialog, _ ->
            dialog.cancel()
            Toast.makeText(applicationContext, "Your dialog has been closed", Toast.LENGTH_LONG)
            .show()
        }
        builder.setNegativeButton("No") { _, _ ->}
        val alertDialog: AlertDialog = builder.create()
        alertDialog.show()
    }
}

4단계: AndroidManifest.xml 확인

AndroidManifest.xml에는 별도의 권한 설정이 필요하지 않습니다. 아래와 같이 MainActivity가 정상적으로 등록되어 있는지만 확인하면 됩니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.q11">
    <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>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 Android 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 실행(Run) Kotlin으로 Android에서 제목 없는 AlertDialog 만드는 방법 아이콘을 클릭하세요. 목록에서 연결된 모바일 기기를 선택하면, 기기 화면에 아래와 같은 결과가 표시됩니다.

Kotlin으로 Android에서 제목 없는 AlertDialog 만드는 방법

Kotlin으로 Android에서 제목 없는 AlertDialog 만드는 방법

앱이 실행되면 제목 없이 메시지와 두 개의 버튼만 있는 AlertDialog가 나타납니다. [Yes] 버튼을 누르면 다이얼로그가 닫히면서 "Your dialog has been closed"라는 토스트 메시지가 표시되고, [No] 버튼을 누르면 아무 동작 없이 다이얼로그가 유지됩니다.