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

Kotlin으로 Android 커스텀 알럿 다이얼로그(AlertDialog) 만드는 방법 – 단계별 완벽 가이드

Android 앱을 개발하다 보면 기본 제공되는 알럿 다이얼로그보다 앱의 디자인에 어울리는 커스텀(Custom) 다이얼로그가 필요한 경우가 많습니다. 이 글에서는 Kotlin을 활용해 Android 앱에서 자신만의 스타일을 적용한 커스텀 알럿 다이얼로그를 만드는 과정을 단계별로 살펴보겠습니다.

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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="MainActivity">
    <Button
        android:id="@+id/buttonShowCustomDialog"
        style="@android:style/Widget.DeviceDefault.Button.Inset"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="131dp"
        android:onClick="exit"
        android:text="Click"
        android:textStyle="normal|bold" />
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/buttonShowCustomDialog"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="86dp"
        android:gravity="center"
        android:text="CLICK TO VIEW CUSTOM ALERT DIALOG"
        android:textSize="18sp"
        android:textStyle="normal|bold" />
</RelativeLayout>

3단계: MainActivity.kt 구현하기

커스텀 다이얼로그의 핵심 로직입니다. Dialog 클래스를 사용해 별도로 만든 레이아웃(customdialog)을 다이얼로그 화면으로 지정하고, 확인 버튼 클릭 시 다이얼로그를 닫으면서 토스트 메시지를 표시합니다.

import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    private val context: Context = this
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
    }
    fun exit(view: View) {
        val dialog = Dialog(context)
        dialog.setContentView(R.layout.customdialog)
        val dialogButton = dialog.findViewById<Button>(R.id.dialogButtonOK)
        dialogButton.setOnClickListener {
            dialog.dismiss()
            Toast.makeText(applicationContext, "Dismissed..!!", Toast.LENGTH_SHORT).show()
        }
        dialog.show()
    }
}

코드 설명

  • Dialog(context): 기본 Dialog 객체를 생성합니다.
  • setContentView(R.layout.customdialog): 미리 만들어 둔 커스텀 레이아웃 XML을 다이얼로그에 적용합니다.
  • dialog.dismiss(): 다이얼로그를 닫습니다.
  • Toast.makeText(...): 다이얼로그가 닫혔다는 피드백을 사용자에게 전달합니다.

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) 만드는 방법 – 단계별 완벽 가이드

확인 버튼을 누르면 다이얼로그가 닫히면서 "Dismissed..!!" 토스트 메시지가 출력됩니다.

Kotlin으로 Android 커스텀 알럿 다이얼로그(AlertDialog) 만드는 방법 – 단계별 완벽 가이드

마무리

이처럼 Kotlin에서는 Dialog 클래스와 별도의 레이아웃 XML만 있으면 손쉽게 커스텀 알럿 다이얼로그를 구현할 수 있습니다. 여기에 더해 버튼 색상 변경, 애니메이션 효과 추가, 다이얼로그 외부 터치 시 취소 처리 등을 응용하면 더욱 완성도 높은 UI를 만들 수 있습니다. 실제 프로젝트에서는 DialogFragment를 활용하면 화면 회전 등 구성 변경 시에도 다이얼로그 상태를 안전하게 유지할 수 있으니 참고하세요.