Kotlin을 사용한 Android 경고 대화상자
이 튜토리얼에서는 Alert Dialog에 대해 논의하고 Kotlin을 사용하여 Android 애플리케이션에 구현합니다.
경고 대화 상자
경고 대화 상자는 화면에 팝업되는 창입니다. 일반적으로 일부 정보를 표시하고 사용자 작업을 요청합니다. 경고 대화 상자를 구성하는 세 가지 핵심 구성 요소가 있습니다.
- 제목 텍스트
- 메시지 텍스트
- 버튼 - 세 가지 유형의 버튼이 있습니다: 포지티브, 네거티브 및 뉴트럴
AlertDialog를 생성하기 위해 AlertDialog.Builder
내부 클래스를 사용합니다.
val alertDialogBuilder = AlertDialog.Builder(this)
생성자 내부에 컨텍스트를 전달합니다. 선택적으로 다른 매개 변수인 경고 대화 상자 스타일을 전달할 수 있습니다.
경고 대화 상자 방법
AlertDialog에서 사용할 수 있는 일부 메서드입니다.
- 제목 설정
- setMessage
- setIcon
- setCustomTitle - 여기에서 경고 대화 상자의 제목 부분에 배치될 사용자 정의 보기를 전달할 수 있습니다.
- setPositiveButton - 여기에 문자열 이름과 Button, 클릭 콜백 메서드를 전달합니다.
- setView - 경고 대화 상자 안에 사용자 지정 보기를 추가하는 데 사용됩니다.
- setList - 목록 형식으로 표시될 문자열 배열을 설정하는 데 사용됩니다.
- setMultiChoiceList - 다시 배열을 설정할 수 있지만 이번에는 CheckBox 덕분에 목록에서 여러 항목을 선택할 수 있습니다.
- setPositiveButtonIcon - 버튼 옆에 아이콘 설정
- show() - AlertDialog를 표시하는 데 사용
- setDismissListener - 이 내부에서 경고 대화 상자가 닫힐 때 트리거되는 논리를 설정할 수 있습니다.
- setShowListener - 경고 대화 상자가 닫힐 때 트리거할 논리를 설정합니다.
- setCanceable - 부울 값이 필요합니다. 기본적으로 모든 경고 대화 상자는 버튼을 클릭하거나 외부를 터치하면 취소할 수 있습니다. 이 메서드가 false로 설정되면 dialog.cancel() 메서드를 사용하여 대화를 명시적으로 취소해야 합니다.
경고 대화 상자 Kotlin 코드
Android Studio 프로젝트에서 AlertDialog를 사용하려면 다음 클래스를 가져옵니다.
import android.support.v7.app.AlertDialog;
다음 Kotlin 코드는 간단한 경고 대화 상자를 만드는 데 사용됩니다.
val builder = AlertDialog.Builder(this)
builder.setTitle("Androidly Alert")
builder.setMessage("We have a message")
//builder.setPositiveButton("OK", DialogInterface.OnClickListener(function = x))
builder.setPositiveButton(android.R.string.yes) { dialog, which ->
Toast.makeText(applicationContext,
android.R.string.yes, Toast.LENGTH_SHORT).show()
}
builder.setNegativeButton(android.R.string.no) { dialog, which ->
Toast.makeText(applicationContext,
android.R.string.no, Toast.LENGTH_SHORT).show()
}
builder.setNeutralButton("Maybe") { dialog, which ->
Toast.makeText(applicationContext,
"Maybe", Toast.LENGTH_SHORT).show()
}
builder.show()
builder.show()
는 화면에 경고 대화 상자를 표시합니다. setPositiveButton
함수 내에서 버튼을 클릭할 때 트리거되는 Kotlin 함수와 함께 Button 텍스트를 전달합니다. 이 함수는 DialogInterface.OnClickListener()
인터페이스의 일부입니다. 함수 타입은 (DialogInterface, Int) -> Unit
입니다. DialogInterface는 Dialog의 인스턴스이고 Int는 클릭한 버튼의 ID입니다. 위의 코드에서 우리는 이 함수를 Higher Order Kotlin 함수로 표현했습니다. dialog
및 which
는 두 인수를 나타냅니다. 인수가 사용되지 않는 경우 _를 전달하여 함수를 개선할 수 있습니다. 기능은 다음과 같습니다.
builder.setPositiveButton(android.R.string.yes) { _,_ ->
Toast.makeText(applicationContext,
android.R.string.yes, Toast.LENGTH_SHORT).show()
}
또는 AlertDialog 클래스 인스턴스를 통해 대화 상자를 표시할 수도 있습니다. builder.show()
를 다음으로 교체합니다.
val alertDialog = builder.create()
alertDialog.show()
각 버튼에 대해 버튼 클릭 리스너 함수를 정의하는 대신 고차 함수도 별도로 정의할 수 있습니다.
val positiveButtonClick = { dialog: DialogInterface, which: Int ->
Toast.makeText(applicationContext,
android.R.string.no, Toast.LENGTH_SHORT).show()
}
이제 setPositiveButton
Kotlin 함수 내에서 이 val
속성을 다음과 같이 설정합니다.
builder.setPositiveButton("OK", DialogInterface.OnClickListener(function = positiveButtonClick))
//or
builder.setPositiveButton(android.R.string.yes, positiveButtonClick)
버튼 클릭에 대한 작업을 유지하지 않으려면 함수 대신 null을 전달할 수 있습니다.
Kotlin은 위 코드의 가독성을 개선할 수 있는 더 많은 기능을 가지고 있습니다.
단순 경고 대화 상자 Kotlin 코드
with
기능을 사용하여 Kotlin 코드의 가독성을 향상하여 Alert Dialog를 만들 수 있습니다.
fun basicAlert(view: View){
val builder = AlertDialog.Builder(this)
with(builder)
{
setTitle("Androidly Alert")
setMessage("We have a message")
setPositiveButton("OK", DialogInterface.OnClickListener(function = positiveButtonClick))
setNegativeButton(android.R.string.no, negativeButtonClick)
setNeutralButton("Maybe", neutralButtonClick)
show()
}
}
다음 섹션에서는 AlertDialog에서 다음 기능을 구현할 Android 애플리케이션을 만들 것입니다.
- 간단한 알림 대화 상자
- 아이콘 및 버튼 사용자 정의가 있는 알림 대화 상자
- 목록이 있는 경고 대화 상자
- 다중 선택 목록이 있는 경고 대화 상자
- 스타일이 있는 경고 대화 상자
- 사용자 지정 스타일이 있는 경고 대화 상자
- EditText가 있는 경고 대화 상자
Android 스튜디오 프로젝트 구조
1. XML 레이아웃 코드
activity_main.xml 레이아웃의 코드는 다음과 같습니다.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/btnBasicAlert"
android:layout_width="wrap_content"
android:onClick="basicAlert"
android:layout_height="wrap_content"
android:text="BASIC ALERT DIALOG" />
<Button
android:id="@+id/btnAlertWithIconsAndCustomize"
android:layout_width="wrap_content"
android:onClick="withIconAndCustomise"
android:layout_height="wrap_content"
android:text="WITH ICON AND CUSTOMIZATION" />
<Button
android:id="@+id/btnAlertWithItems"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="withItems"
android:text="WITH ITEMS" />
<Button
android:id="@+id/btnAlertWithMultiChoiceList"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="withMultiChoiceList"
android:text="WITH MULTI CHOICE LIST" />
<Button
android:id="@+id/btnAlertWithStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="withStyle"
android:text="WITH STYLE" />
<Button
android:id="@+id/btnAlertWithCustomStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="withCustomStyle"
android:text="WITH CUSTOM STYLE" />
<Button
android:id="@+id/btnAlertWithButtonCentered"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="withButtonCentered"
android:text="WITH BUTTON CENTERED" />
<Button
android:id="@+id/btnAlertWithEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="withEditText"
android:text="WITH EDIT TEXT" />
</LinearLayout>
각 버튼에 대해 함수 이름으로 android:onClick
속성을 설정했습니다. 이러한 Kotlin 함수는 MainActivity.kt 클래스에서 트리거됩니다. 한 번에 하나씩 논의하겠습니다.
2. Kotlin 주요 활동 코드
위에서 첫 번째 경고 대화 상자를 이미 만들었습니다. MainActivity.kt가 어떻게 보이는지 봅시다.
package net.androidly.androidlyalertdialog
import android.content.DialogInterface
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.app.AlertDialog
import android.view.View
import android.widget.Toast
class MainActivity : AppCompatActivity() {
val positiveButtonClick = { dialog: DialogInterface, which: Int ->
Toast.makeText(applicationContext,
android.R.string.yes, Toast.LENGTH_SHORT).show()
}
val negativeButtonClick = { dialog: DialogInterface, which: Int ->
Toast.makeText(applicationContext,
android.R.string.no, Toast.LENGTH_SHORT).show()
}
val neutralButtonClick = { dialog: DialogInterface, which: Int ->
Toast.makeText(applicationContext,
"Maybe", Toast.LENGTH_SHORT).show()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun basicAlert(view: View){
val builder = AlertDialog.Builder(this)
with(builder)
{
setTitle("Androidly Alert")
setMessage("We have a message")
setPositiveButton("OK", DialogInterface.OnClickListener(function = positiveButtonClick))
setNegativeButton(android.R.string.no, negativeButtonClick)
setNeutralButton("Maybe", neutralButtonClick)
show()
}
}
}
3. 아이콘 및 사용자 정의가 있는 경고 대화 상자
val builder = AlertDialog.Builder(this)
with(builder) {
setTitle("Icon and Button Color")
setMessage("We have a message")
setPositiveButton("OK", null)
setNegativeButton("CANCEL", null)
setNeutralButton("NEUTRAL", null)
setPositiveButtonIcon(resources.getDrawable(android.R.drawable.ic_menu_call, theme))
setIcon(resources.getDrawable(android.R.drawable.ic_dialog_alert, theme))
}
val alertDialog = builder.create()
alertDialog.show()
val button = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE)
with(button) {
setBackgroundColor(Color.BLACK)
setPadding(0, 0, 20, 0)
setTextColor(Color.WHITE)
}
getButton
을 사용하여 각각의 상수를 설정하여 버튼을 검색할 수 있습니다. Button이 검색되면 위와 같이 사용자 정의할 수 있습니다.
4. 항목이 있는 경고 대화 상자
fun withItems(view: View) {
val items = arrayOf("Red", "Orange", "Yellow", "Blue")
val builder = AlertDialog.Builder(this)
with(builder)
{
setTitle("List of Items")
setItems(items) { dialog, which ->
Toast.makeText(applicationContext, items[which] + " is clicked", Toast.LENGTH_SHORT).show()
}
setPositiveButton("OK", positiveButtonClick)
show()
}
}
setItems 내에서 Kotlin 배열을 전달합니다. which
인수는 목록에서 클릭한 요소의 인덱스를 나타냅니다.
5. 다중 선택 목록이 있는 경고 대화 상자
fun withMultiChoiceList(view: View) {
val items = arrayOf("Microsoft", "Apple", "Amazon", "Google")
val selectedList = ArrayList<Int>()
val builder = AlertDialog.Builder(this)
builder.setTitle("This is list choice dialog box")
builder.setMultiChoiceItems(items, null
) { dialog, which, isChecked ->
if (isChecked) {
selectedList.add(which)
} else if (selectedList.contains(which)) {
selectedList.remove(Integer.valueOf(which))
}
}
builder.setPositiveButton("DONE") { dialogInterface, i ->
val selectedStrings = ArrayList<string>()
for (j in selectedList.indices) {
selectedStrings.add(items[selectedList[j]])
}
Toast.makeText(applicationContext, "Items selected are: " + Arrays.toString(selectedStrings.toTypedArray()), Toast.LENGTH_SHORT).show()
}
builder.show()
}
위의 코드에서 선택 항목을 정수 배열 목록에 저장하고 다시 검색하여 Toast 메시지에 표시합니다.
6. 스타일이 있는 경고 대화 상자
fun withStyle(view: View) {
val builder = AlertDialog.Builder(ContextThemeWrapper(this, android.R.style.Holo_SegmentedButton))
with(builder)
{
setTitle("Androidly Alert")
setMessage("We have a message")
setPositiveButton("OK", DialogInterface.OnClickListener(function = positiveButtonClick))
setNegativeButton(android.R.string.no, negativeButtonClick)
setNeutralButton("Maybe", neutralButtonClick)
show()
}
}
ContextThemeWrapper를 사용하지 않으면 경고 대화 상자가 전체 화면에 표시됩니다.
7. 사용자 정의 스타일이 있는 경고 대화 상자
styles.xml 파일에 다음 코드를 추가합니다.
<style name="AlertDialogCustom" parent="@android:style/Theme.Material.Dialog">
<item name="android:textColor">@android:color/white</item>
<item name="android:textStyle">bold</item>
<item name="android:headerDividersEnabled">true</item>
<item name="android:background">@android:color/holo_blue_dark</item>
</style>
다음은 Kotlin 함수입니다.
fun withCustomStyle(view: View) {
val builder = AlertDialog.Builder(ContextThemeWrapper(this, R.style.AlertDialogCustom))
with(builder)
{
setTitle("Androidly Alert")
setMessage("We have a message")
setPositiveButton("OK", DialogInterface.OnClickListener(function = positiveButtonClick))
setNegativeButton(android.R.string.no, negativeButtonClick)
setNeutralButton("Maybe", neutralButtonClick)
show()
}
}
8. 버튼이 중앙에 있는 경고 대화 상자
fun withButtonCentered(view: View) {
val alertDialog = AlertDialog.Builder(this).create()
alertDialog.setTitle("Title")
alertDialog.setMessage("Message")
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Yes"
) { dialog, which -> dialog.dismiss() }
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "No"
) { dialog, which -> dialog.dismiss() }
alertDialog.show()
val btnPositive = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
val btnNegative = alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE)
val layoutParams = btnPositive.layoutParams as LinearLayout.LayoutParams
layoutParams.weight = 10f
btnPositive.layoutParams = layoutParams
btnNegative.layoutParams = layoutParams
}
9. 텍스트 편집이 있는 경고 대화 상자
사용자 정의 레이아웃 alert_dialog_with_edittext.xml의 코드는 다음과 같습니다.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter the text here"/>
</LinearLayout>
fun withEditText(view: View) {
val builder = AlertDialog.Builder(this)
val inflater = layoutInflater
builder.setTitle("With EditText")
val dialogLayout = inflater.inflate(R.layout.alert_dialog_with_edittext, null)
val editText = dialogLayout.findViewById<EditText>(R.id.editText)
builder.setView(dialogLayout)
builder.setPositiveButton("OK") { dialogInterface, i -> Toast.makeText(applicationContext, "EditText is " + editText.text.toString(), Toast.LENGTH_SHORT).show() }
builder.show()
}
Android 스튜디오 프로젝트 다운로드: AndroidlyAlertDialog