Android Application
Kotlin 대화상자(Dialog) : 알림 대화상자(AlertDialog) 체크박스(Check Box)형
작성자 임베디드코리아
작성일23-09-25 01:09
조회1,636회
댓글0건
------------------------------------------------------------------------------------
activity_main.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/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Dialog띄우기" />
</androidx.constraintlayout.widget.ConstraintLayout>
------------------------------------------------------------------------------------
MainActivity.kt
------------------------------------------------------------------------------------
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//setContentView(R.layout.activity_main)
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
binding.button.setOnClickListener {
val items = arrayOf("곰", "사자", "호랑이", "독수리")
val selectedItemIndex = ArrayList<Int>()
val builder = AlertDialog.Builder(this)
.setTitle("좋아하는 동물?")
.setMultiChoiceItems(items, null){ dialog, which, bool ->
if(bool){
selectedItemIndex.add(which)
}else if(selectedItemIndex.contains(which)){
selectedItemIndex.remove(which)
}
}
.setPositiveButton("확인",
DialogInterface.OnClickListener { dialog, which ->
val selectedItems = ArrayList<String>()
for(i in selectedItemIndex){
selectedItems.add(items[i])
}
Toast.makeText(this, selectedItems.toString(), Toast.LENGTH_SHORT).show()
})
builder.show()
}
}
}
------------------------------------------------------------------------------------
build.gradle(Module) : build.gradle.kts
-------------------------------------------------------------------------------------
// 안드로이드 스튜디오 4.0 이상
android {
...
buildFeatures {
viewBinding = true
}
}