[안드로이드 / Kotlin] 라디오버튼 Dialog

2021. 8. 31. 16:48·Android
반응형

안드로이드에서 제공하는 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
'Android' 카테고리의 다른 글
  • [안드로이드 / Kotlin] windowLightStatusBar
  • [안드로이드 / Kotlin] 뒤로가기 두번 눌러서 종료하기
  • [안드로이드 / Kotlin] Array와 ArrayList 변환
  • [안드로이드 / Kotlin] DatePickerDialog
서주냥
서주냥
간단한 것도 기록하는 습관을 가지자
  • 서주냥
    DroidLog
    서주냥
  • 전체
    오늘
    어제
    • 전체보기 (58)
      • 알고리즘 (12)
        • 백준 (4)
        • 프로그래머스 (5)
        • 개념 (3)
      • Android (43)
        • Compose (1)
      • Java (2)
      • Kotlin (1)
  • 링크

    • GitHub
  • 인기 글

  • 태그

    안드로이드
    알고리즘
    블루투스
    BLE
    Hilt
    이진 탐색
    뷰모델
    최단 경로
    자바
    debounce
    viewpager2
    코루틴
    Clean Architecture
    다이나믹 프로그래밍
    FusedLocationProviderClient
    백준
    벨만 포드
    moshi
    코틀린
    Coroutine
    textunit
    RecyclerView
    프로그래머스
    투 포인터
    클린 아키텍처
    SnackBar
    viewmodel
    reified
    ConstraintLayout
    Coroutine Flow
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
서주냥
[안드로이드 / Kotlin] 라디오버튼 Dialog
상단으로

티스토리툴바