코딩하는 개굴이

[안드로이드] RadioButtond 은 id 지정 안하면..? 본문

안드로이드

[안드로이드] RadioButtond 은 id 지정 안하면..?

개굴이모자 2023. 2. 26. 23:48
반응형

개발하면서 Radio Button 을 사용하게 되었는데, 생각 외로 이상한 현상이 있었다.

어느 버튼이 눌린 것인지 알아야하는거면 position 으로 radio group 에서 listener 를 달면 되겠지? 라고 생각하며 xml 을 이리 짜둔 상태에서 실행해보니, 재미있는 현상이 발생하더라.

동시에 여러개가 선택되는 것이 아닌가?

이게 뭔일이래…

(본래 Radio Button 이란 CheckBox 와는 달리, 한번에 하나만 선택될 수 있도록 하는 특징이 있다.)

 

생각보다 원인은 쉬운 것이었다. 아래 xml 에서 어떤 것이 잘못된 건지 알 수 있을까?

	<LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <RadioGroup
                android:id="@+id/radio_group"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <RadioButton
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="item 1" />

                <RadioButton
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="item 2" />

                <RadioButton
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="item 3" />
            </RadioGroup>
        </LinearLayout>

 

바로, RadioButton 에 id 를 지정하지 않은 것이 원인이었다.

따라서 listener 도 돌지 않고, 한번에 하나만 선택되는 것도 되지 않았던 것이다.

아래처럼 listener 를 달면, i 가 position 값인줄 알았건만, id 값을 넣어주면 정상 동작하는 것을 볼 수 있었다.

 

binding.radioGroup.setOnCheckedChangeListener { radioGroup, i ->               //... }

 

 

파라미터의 역할을 잘 보자…

 

 

참고 링크


Uploaded by

N2T
반응형
Comments