Android Application

Kotlin 대화상자(Dialog) : 알림 대화상자(AlertDialog) 라디오 버튼형

작성자 임베디드코리아 작성일23-09-25 01:15 조회1,568회 댓글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="wrap_content"
        android:layout_height="wrap_content"
        android:text="대화상자 라디오버튼"
        android:textSize="30dp"
        tools:layout_editor_absoluteX="156dp"
        tools:layout_editor_absoluteY="240dp" />

</androidx.constraintlayout.widget.ConstraintLayout>

------------------------------------------------------------------------------------
    MainActivity.kt
------------------------------------------------------------------------------------
class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //etContentView(R.layout.activity_main)

        binding = ActivityMainBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)

        binding.button.setOnClickListener {
            val items = arrayOf("곰", "사자", "호랑이", "독수리")
            var selectedItem: String? = null
            val builder = AlertDialog.Builder(this)
                .setTitle("좋아하는 동물?")
                .setSingleChoiceItems(items, -1){ dialog, which ->
                    selectedItem = items[which]
                }
                .setPositiveButton("확인",
                    DialogInterface.OnClickListener { dialog, which ->
                        Toast.makeText(this, selectedItem, Toast.LENGTH_SHORT).show()
                    })
            builder.show()
        }
    }
}

------------------------------------------------------------------------------------
  build.gradle(Module) : build.gradle.kts
-------------------------------------------------------------------------------------
// 안드로이드 스튜디오 4.0 이상
android {
    ...
    buildFeatures {
        viewBinding = true
    }
}