RadioButton的一个bug

昨天发现了一个RadioButton 的bug,出现bug的代码如下:

 1 <RadioGroup
 2     android:layout_width="wrap_content"
 3     android:layout_height="wrap_content"
 4     android:orientation="horizontal"
 5     >
 6     <RadioButton
 7         android:layout_width="wrap_content"
 8         android:layout_height="wrap_content"
10         android:checked="true"
11         android:text="初中"/>
12     <RadioButton
13         android:layout_width="wrap_content"
14         android:layout_height="wrap_content"
16         android:text="高中"/>
17     <RadioButton
18         android:layout_width="wrap_content"
19         android:layout_height="wrap_content"
21         android:text="大学"/>
22 </RadioGroup>

上面的这段代码只是布局文件里最基本的代码,简单的RadioGroup中加入了三个RadioButton代码。

用真机和虚拟机测试的时候就出现了bug,如下图:

刷新布局时只有“初中”按钮被选中,但是点击了“大学”之后,“初中”按钮不被取消,只有“高中”和“大学”两个按钮互相切换。

我是用的是android studio1.4,API版本17,虚拟机版本是android4.2,真机版本是android4.1,虚拟机和真机都是这个bug。

经过了一番挣扎以及尝试,终于找到的这个bug的原因:

RadioButton每个按钮必须要加android:id这个属性,id属性名只要遵循标识符命名规则就OK,id不重名但是必须得加上,着实让人很无语。

<RadioButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/rb_01"
    android:text="大学"/>

只写布局文件的时候,一定要注意这个细节!!

原文地址:https://www.cnblogs.com/ccshxt/p/5224642.html