RadioGroup和RadioButton 的使用

RadioGroup和RadioButton 的简单使用举例

简单的做个开关举例, 布局如下:

<RadioGroup
	android:id="@+id/rgSwitch"
	android:layout_width="match_parent"
	android:layout_height="50dp"
	android:layout_marginTop="10dp"
	android:background="#63C4C4C4"
	android:orientation="horizontal">

	<RadioButton
		android:id="@+id/rbEnable"
		android:layout_width="0dp"
		android:layout_height="match_parent"
		android:layout_weight="1"
		android:gravity="center_vertical"
		android:text="可用"
		android:textAllCaps="false"
		android:textColor="#000"
		android:textSize="18sp"
		android:textStyle="bold"
		android:theme="@style/RadioButtonStyle" />

	<View
		android:layout_width="1dp"
		android:layout_height="match_parent"
		android:background="#C4C4C4" />

	<RadioButton
		android:id="@+id/rbUnEnable"
		android:layout_width="0dp"
		android:layout_height="match_parent"
		android:layout_weight="1"
		android:checked="true"
		android:gravity="center_vertical"
		android:text="不可用"
		android:textAllCaps="false"
		android:textColor="#000"
		android:textSize="18sp"
		android:textStyle="bold"
		android:theme="@style/RadioButtonStyle" />
</RadioGroup>

java代码如下:

// 初始化控件
RadioGroup rgSwitch = (RadioGroup) findViewById(R.id.rgSwitch);
// 设置监听器
rgSwitch.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId) {
			// 判断点击的是那个RadioButton
			switch (checkedId) {
				// 不同的RadioButton做不同的事
				case R.id.rbEnable:
					bigDownloading.setEnable(true);
					break;
				case R.id.rbUnEnable:
					bigDownloading.setEnable(false);
					break;
			}
		}
	});

RadioButton默认选中

在RadioButton的属性中添加如下代码即可:

android:checked="true"

给RadioButton更换主题

如图所示, RadioButton在选中和未选中的状态时, 都对应不同的颜色, 有时候根据需求需要改成其他的颜色:
RadioButton默认主题色
可以看到这里默认是灰色和粉色的, 现在需要改成粉色和蓝色的, 步骤如下:

1. 添加主题

需要自定义一个主题, 指定未选中状态和选中状态的颜色.
在res目录下找到values目录, 在里面找到styles.xml文件, 添加如下代码

<!--RadioButton更换主题色-->
<style name="RadioButtonStyle" parent="Theme.AppCompat.Light">
    <!--未选中时的颜色-->
    <item name="colorControlNormal">#EBB2B2</item>
    <!--选中时的颜色-->
    <item name="colorControlActivated">#416CE7</item>
</style>
2. 使用主题

在xml布局中给RadioButton添加theme属性:

android:theme="@style/RadioButtonStyle"

到这里就结束了, 看结果:
RadioButton更换后的主题色

发布了25 篇原创文章 · 获赞 2 · 访问量 1496

猜你喜欢

转载自blog.csdn.net/geaosu2/article/details/104090542