본문 바로가기
개발노트/Android

[Kotlin] Custom Dialog 사용하기

by 전지적진영시점 2023. 2. 17.
반응형

개발 환경

---------------------------------

OS : Mac

개발 툴 : Android Studio

개발 언어 : Kotlin

targetSdk : 31

minSdk : 23

---------------------------------

 

안녕하세요 이번 포스팅에서는 

안드로이드 프로젝트에서 Custom Dialog 를 구현하겠습니다

 

준비물 - android studio, 손가락

 

AlertDialog 클래스를 사용할건데 

Android dev 문서에는 

 

"하나, 둘 또는 세 개의 버튼을 표시할 수 있는 Dialog의 하위 클래스입니다"

 

라고 정의하네요

 

먼저 AlertDialog의 객체를 생성해줍니다.

 

함수를 호출하면서 실행 전에 객체를 초기화할테니 일단 null 값을 줍시다.

var alertDialog : AlertDialog? = null

 

 

아래 코드는 ok 버튼 하나 있는 dialog 입니다.

 

fun dialog() {
    alertDialog = AlertDialog.Builder(context)
        .setTitle(context.resources.getString(R.string.notice))
        .setMessage(message)
        .setPositiveButton(context.resources.getString(R.string.ok)) { _: DialogInterface, _: Int -> }
        .show()
}

각 라인의 메서드들을 아래와 같이 설명하겠습니다. 아주 간단하오

 

  •  setTitle : 알림 제목이 표시되는 부분, return type은 string
  •  setMessage : 알림 내용이 표시되는 부분 , return type은 string
  •  setPositiveButton : 버튼
  •  setNegativeButton : 버튼
  •  show : 실행 메서드

 

근데 setPositiveButton 뒤에 붙어 있는

{ _: DialogInterface, _: Int -> }

이 부분이 뭐냐 

 

버튼에 대한 이벤트를 구현할 수 있는 부분입니다.

 

아래처럼 구현할 수 있습니다.

.setPositiveButton(R.string.ok) { _, _ ->
    Log.d("TAG","Success")
}.show()

 

Dialog 창에 확인, 취소 버튼 둘 다 넣고 싶다 한다면 아래와 같이 setNegativeButton을 추가하시면 됩니다.

물론  setNeagtiveButton에도 event를 넣을 수 있습니다.

alertDialog = AlertDialog.Builder(context)
    .setTitle(context.resources.getString(R.string.notice))
    .setMessage(message)
    .setPositiveButton(context.resources.getString(R.string.ok)) { _: DialogInterface, _: Int -> }
    .setNegativeButton(context.resources.getString(R.string.cancel)) { _: DialogInterface, _: Int -> }
    .show()

 

 

근데 나는 메세지만 표시하고 버튼 없어도 된다 ! 하시면

 

alertDialog = AlertDialog.Builder(context)
    .setTitle(context.resources.getString(R.string.notice))
    .setMessage(message)
    .show()

 

이렇게 setMessage() 만 넣고 가셔도 잘 작동합니다

반응형

댓글