android 单选按钮
单选按钮
·
单选按钮RadioButton同一组包含在同一个RadioGroup中,当点击RadioButton时会触发onClick事件。另外,RadioGroup会触发CheckChange事件,当RadioButton选择改变时触发。触发顺序为先触发CheckChange事件然后是Click事件。
测试代码
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.w2_11);
final TextView tv1 = (TextView) findViewById(R.id.w2_11_tv1) ;
final RadioButton rb1 = (RadioButton) findViewById(R.id.w2_11_rb1) ;
final RadioButton rb2 = (RadioButton) findViewById(R.id.w2_11_rb2) ;
RadioGroup rg1 = (RadioGroup) findViewById(R.id.w2_11_rg1) ;
rg1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId == rb1.getId()){
tv1.setText("女change") ;
}else if(checkedId == rb2.getId()){
tv1.setText("男change") ;
}else{
tv1.setText("change") ;
}
}
}) ;
rb1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
tv1.setText("女"+tv1.getText().toString()) ;
}
}) ;
rb2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
tv1.setText("男"+tv1.getText().toString()) ;
}
}) ;
}
xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/w2_11_tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="请选择性别" />
<RadioGroup
android:id="@+id/w2_11_rg1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/w2_11_rb1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:text="女" />
<RadioButton
android:id="@+id/w2_11_rb2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:text="男" />
</RadioGroup>
</LinearLayout>
更多推荐
已为社区贡献10条内容
所有评论(0)