Android按钮控件之RadioGroup和RadioButton

1,RadioGroup是RadioButton的一个集合,能够实现多选一。

2,RadioGroup常用属性:

android:orientation="vertical"、android:orientation="horizontal"

 //作用:决定当前RadioGroup中RadioButton以什么形式排列。

3,RadioButton常用属性:

android:checked="false"  //当前CheckBox是否被选中,默认为false。

4,RadioButton和RadioGroup的关系:
   a、RadioButton表示单个圆形单选框,而RadioGroup是可以容纳多个RadioButton的容器
   b、每个RadioGroup中的RadioButton同时只能有一个被选中
   c、不同的RadioGroup中的RadioButton互不相干,即如果组A中有一个选中了,组B中依然可以有一个被选中
   d、大部分场合下,一个RadioGroup中至少有2个RadioButton
   e、大部分场合下,一个RadioGroup中的RadioButton默认会有一个被选中,并建议您将它放在RadioGroup中的起始位置

5,layout中的布局文件:

 

<span style="font-size:18px;"><RadioGroup 
       android:id="@+id/radioGrup1"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:orientation="vertical">
       
    <RadioButton
        android:id="@+id/radioButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="男" 
        android:checked="true"/>

    <RadioButton
        android:id="@+id/radioButton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="女"
        android:checked="false" />

    </RadioGroup> </span>


6,java类中的代码:

<span style="font-size:18px;">public class MainActivity extends Activity implements OnCheckedChangeListener {

	private RadioGroup rg;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		rg = (RadioGroup) findViewById(R.id.radioGrup1);

		// 通过实现接口的方式来实现监听事件
		rg.setOnCheckedChangeListener(this);
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {

		// 判断对哪个按钮实现了监听
		switch (checkedId) {
		case R.id.radioButton1:
			Log.i("tag", "你当前是一个男孩");
			break;

		case R.id.radioButton2:
			Log.i("tag", "你当前是一个女孩");
			break;
		default:
		}
	}

}</span>


注意:在实现接口时,要把导入的包:import android.widget.CompoundButton.OnCheckedChangeListener

改为:import android.widget.RadioGroup.OnCheckedChangeListener。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值