반응형
안드로이드에서 제공하는 AlertDialog를 이용하면 여러 종류의 다이얼로그를 구현할 수 있습니다.
그 중 라디오버튼 다이얼로그를 간단히 만드는 법을 알아보도록 하겠습니다.
<startRadioButtonDialog()>
fun startRadioButtonDialog(context: Context, items: Array<String>, title: String, index: Int = -1) {
var selectedIndex = index // 선택된 아이템 index
val dialog = AlertDialog.Builder(context, android.R.style.Theme_DeviceDefault_Light_Dialog_Alert)
.apply {
setTitle(title)
setSingleChoiceItems(items, index, DialogInterface.OnClickListener { dialogInterface, i ->
selectedIndex = i
})
setNeutralButton("선택", DialogInterface.OnClickListener { dialogInterface, i ->
println("selectedIndex = $selectedIndex")
if(selectedIndex >= 0) { // 특정 아이템을 선택
Toast.makeText(context, "${items[selectedIndex]} 선택됨.", Toast.LENGTH_SHORT).show()
}
// 선택에 따른 이벤트 작성
})
setCancelable(true)
show()
}
}
위 함수를 이용해 간단한 라디오버튼 다이얼로그를 띄워볼 수 있습니다.
함수 매개변수는 context(컨텍스트), items(라디오버튼 아이템 배열), title(다이얼로그 타이틀),
그리고 index(최초 선택되어질 아이템 인덱스)로 구성되어있습니다.
AlertDialog.Builder를 이용해서 다이얼로그를 생성할 수 있습니다.
setSingleChoiceItems 메소드를 이용해서 라디오버튼 초기화 및 selectedIndex 변수를 이용하여
선택에 따른 인덱스를 갱신합니다.
setNeutralButton 메소드를 이용해서 선택한 아이템에 따른 이벤트를 작성하면 됩니다.
반응형
'Android' 카테고리의 다른 글
[안드로이드 / Kotlin] 코드로 문자열 밑줄 표현하기 (0) | 2021.09.04 |
---|---|
[안드로이드 / Kotlin] windowLightStatusBar (0) | 2021.09.01 |
[안드로이드 / Kotlin] 뒤로가기 두번 눌러서 종료하기 (0) | 2021.08.31 |
[안드로이드 / Kotlin] Array와 ArrayList 변환 (0) | 2021.08.31 |
[안드로이드 / Kotlin] DatePickerDialog (0) | 2021.08.29 |