本文将主要介绍RadioButton的使用方法:
- RadioButton的基本使用
- RadioButton的单选组
- 自定义RadioButton样式
- RadioButton的监听事件
————————————————————————————————————————————————————————
1、RadioButton的基本使用
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:text="你喜欢吃苹果嘛?"
android:textSize="18sp" />
效果:
但是此时可以发现该状态下选中后是无法取消的
2、RadioButton的单选组
将两个RadioButton合并为一个RadioGroup,这样就可以实现在一个单选组里进行单选了:
可以设置默认选中:只需要设置android:checked="false"属性即可,(!!!使用该属性一定要设置一个ID,不然无法显示效果)
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="80dp"
android:text="你喜欢吃苹果嘛?"
android:textSize="18sp" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:text="你喜欢吃橘子嘛?"
android:textSize="18sp" />
</RadioGroup>
效果:
3、自定义RadioButton样式
如果要自定义radioButton的样式,可以去创建一个drawable来设置对应的样式
如果要取消radiobutton前面的小圆点可以设置: android:button="@null"
设置初始值:(!!!使用该属性一定要设置一个ID,不然无法显示效果)
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true">
<shape>
<solid android:color="#990412" />
</shape>
</item>
<item android:state_checked="false">
<shape>
<solid android:color="#098412" />
</shape>
</item>
</selector>
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/radio_btn_my"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="80dp"
android:button="@null"
android:text="你喜欢吃苹果嘛?"
android:textSize="22sp"
android:checked="true"
android:background="@drawable/radio_button_select"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:background="@drawable/radio_button_select"
android:button="@null"
android:text="你喜欢吃橘子嘛?"
android:textSize="22sp" />
</RadioGroup>
实现效果:
4、RadioButton的监听事件
当点击状态改变时就弹出一个toast
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
RadioButton radioButton=findViewById(R.id.radio_btn_my);
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Toast.makeText(LayoutActivity.this,"a",Toast.LENGTH_SHORT).show();
}
});
}
效果: