개인 프로젝트를 진행중 간단한 Content를 한 줄을 입력하고 싶은데 Activity나 Fragment로 이동하기에는 한 줄만 입력하기에 효율적이지 않다고 생각이 되었기 때문에 어떻게 하면 좋을지 생각해보고 검색하다가 Alert Dialog를 사용하면 좋겠다라고 생각이 들었습니다!
그래서 이번 포스팅에는 Alert Dialog에 대해서 공부해보겠습니다.
우선 Alert Dialog가 무엇인지 가장먼저 Android 개발자 사이트에서 확인해보겠습니다.
https://developer.android.com/guide/topics/ui/dialogs?hl=ko
대화상자 | Android 개발자 | Android Developers
대화상자는 사용자에게 결정을 내리거나 추가 정보를 입력하라는 메시지를 표시하는 작은 창입니다. 대화상자는 화면을 가득 채우지 않으며 보통은 사용자가 다음으로 계속 진행하기 전에 조
developer.android.com
안드로이드 개발자 문서에서 설명하는 Dialog에 대해서 살펴보겠습니다.
A dialog is a small window that prompts the user to make a decision or enter additional information.
A dialog does not fill the screen and is normally used for modal events that require users to take an action before they can proceed.
> 번역을 해보면
'대화 상자는 사용자에게 결정을 내리거나 추가 정보를 입력하라는 메시지를 표시하는 작은 창입니다.'
'대화 상자는 화면을 채우지 않으며 일반적으로 사용자가 계속하기 전에 조치를 취해야 하는 모달 이벤트에 사용됩니다.'
라고 되어있습니다.
간단하게 말하자면 화면을 채우지 않은 대화상자이며 사용자와 대화를 할 수 있는 작은 창이라고 할 수 있겠습니다.
안드로이드에는 지금 포스팅하고자 하는 AlertDialog와 사용자가 날짜 또는 시간을 선택할 수 있도록 미리 정의된 UI가 있는 대화상자인 DataPickerDialog와 TimePickerDialog가 있습니다.
카카오톡, 당근마켓, 인스타 등등 우리가 일상생활에서도 많이 사용하는 어플에서도 이러한 Dialog창을 이용한것을 쉽게 찾아볼 수 있습니다.
간단한 예제를 통해서 Alert Dialog를 알아보겠습니다.
1. xml 작성하기
아주 간단하게 확인할 수 있도록 예제를 만들어 보겠습니다.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/btn_dialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Alert_Dialog"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
xml파일에서 버튼을 클릭하게 되면 alertDialog창을 보여줄 수 있도록 생성해주었습니다.
2. kt 작성하기
package com.duran.testapp
import android.content.DialogInterface
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.duran.testapp.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private val dialogBtn by lazy { binding.btnDialog }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
dialogBtn.setOnClickListener {
val builder = AlertDialog.Builder(this)
builder.setTitle("Dialog Title") // Dialog창의 Title
.setMessage("Dialog Content") // Dialog창의 Content
// Dialog창의 확인 버튼 클릭 이벤트
.setPositiveButton("확인",
DialogInterface.OnClickListener { dialog, which ->
Toast.makeText(this, "확인", Toast.LENGTH_SHORT).show()
})
// Dialog창의 취소 버튼 클릭 이벤트
.setNegativeButton("취소",
DialogInterface.OnClickListener { dialog, which ->
Toast.makeText(this, "취소", Toast.LENGTH_SHORT).show()
})
// Dialog 띄워주기
builder.show()
}
}
}
코틀린 파일에서 Dialog기능을 구현해보았습니다.
dialogBtn.setOnClickListener { }
앞서 xml파일에서 버튼을 클릭했을때 이벤트가 발생하게 해주었고
val builder = AlertDialog.Builder(this)
AlertDialog를 지금 context에 builder합니다.
builder.setTitle("Dialog Title")
.setMessage("Dialog Content")
.setPositiveButton("확인",
DialogInterface.OnClickListener { dialog, which ->
Toast.makeText(this, "확인", Toast.LENGTH_SHORT).show()
})
.setNegativeButton("취소",
DialogInterface.OnClickListener { dialog, which ->
Toast.makeText(this, "취소", Toast.LENGTH_SHORT).show()
})
builder된 AlertDialog에 필요한 것들을 set해주어야 합니다.
- setTitle은 AlertDialog를 띄울때 작성한 제목을 set
- setMessage는 AlertDialog를 띄울때 작성한 내용, content를 set
- setPositiveButton은 버튼 클릭 시 OK에 대한 이벤트
- setNegativeButton은 버튼 클릭 시 cancel에 대한 이벤트
현재 Ok와 cancel에 대한 버튼 이벤트로 Toast메세지로 구현했지만 필요에 따른 이벤트로 구현해주면 됩니다.
그리고 마지막으로
builder.show()
해주게되면 build한 AlertDialog를 띄워주게 됩니다.
이제 실행 시켜보겠습니다.
버튼을 클릭하게되면 AlertDialog창이 나오게 되고 확인 버튼을 클릭하면 확인, 취소 버튼을 클릭하게 되면 취소라는 Toast메세지가 나오는것을 확인할 수 있습니다!
간단한 예제와 함께 AlertDialog를 알아보았습니다.
'안드로이드 > Kotlin' 카테고리의 다른 글
[Kotlin] Password 정규식 (2) | 2022.09.29 |
---|---|
[Kotlin] Splash Screen(로딩 화면) 만들어보기 (0) | 2022.09.28 |
[Kotlin] Toolbar Custom해보기 (0) | 2022.09.28 |
[Kotlin] Splash 화면 만들기 (0) | 2022.08.16 |
[Kotlin] var와 val의 차이점 (0) | 2022.08.06 |