这两天遇到需要 RadioGroup 和 RadioButton 点击事件处理,记录一下。
1. RadioGroup 监听
先看布局页面,如图所示:
布局很简单,就一个 RadioGroup 包含三个 RadioButton,直接上代码:
<RadioGroup
android:id="@+id/radio_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/male"
android:checked="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:text="男"
/>
<RadioButton
android:id="@+id/female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:text="女"
/>
<RadioButton
android:id="@+id/other"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:text="保密"
/>
</RadioGroup>
测试类代码如下:
public class TestRadioGroupClick extends Activity implements OnCheckedChangeListener {
private RadioGroup radioGroup;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.radio_group);
radioGroup = (RadioGroup) findViewById(R.id.radio_group);
radioGroup.setOnCheckedChangeListener(this);// 当然也可以使用匿名内部类实现
}
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {// Q: 参数 group 暂时还没搞清什么用途
switch (checkedId) {
case R.id.male:
Toast.makeText(this, "male", Toast.LENGTH_SHORT).show();
break;
case R.id.female:
Toast.makeText(this, "female", Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(this, "secret", Toast.LENGTH_SHORT).show();
break;
}
}
}
这样,就可以通过 RadioGroup 来监听每一个 RadioButton 的状态了。
注意:RadioGroup 实现的是 OnCheckedChangeListener 接口,和常见的 OnClickListener 有所不同。
2. RadioButton 监听
除了监听 RadioGroup 整体,也可以单独监听每一个 RadioButton,此时添加的就是 OnClickListener 了!
示例代码:
RadioButton male = (RadioButton) findViewById(R.id.male);
male = (RadioButton) findViewById(R.id.male);
male.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(TestRadioGroupClick.this, "you clicked male", Toast.LENGTH_SHORT).show();
}
});
324

被折叠的 条评论
为什么被折叠?



