zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

安卓开发入门教程-UI控件_RadioButton

安卓入门教程UI开发 控件 RadioButton
2023-09-27 14:27:30 时间

什么是RadioButton、RadioGroup

RadioButton和RadioGroup是用来显示一组单选框的,RadioButton就是单个单选框,RadioGroup就是这个组.

基础样例

1.展示一组单选框

效果图


代码

  1. 布局文件:activity_main.xml
<RadioGroup
    android:id="@+id/radioGroup"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <RadioButton
        android:id="@+id/radioButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="选项1" />

    <RadioButton
        android:id="@+id/radioButton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="选项2" />
</RadioGroup>
  1. activity代码:
//对单选框组设置点击事件,点击按钮时,弹出toast提示
radioGroup.setOnCheckedChangeListener { _, checkedButton ->
    when (checkedButton) {
        R.id.radioButton1 -> toast("选项1")
        R.id.radioButton2 -> toast("选项2")
    }
}

完整代码:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //对单选框组设置点击事件,点击按钮时,弹出toast提示
        radioGroup.setOnCheckedChangeListener { _, checkedButton ->
            when (checkedButton) {
                R.id.radioButton1 -> toast("选项1")
                R.id.radioButton2 -> toast("选项2")
            }
        }
    }

    private fun toast(text: String) = Toast.makeText(this, text, Toast.LENGTH_SHORT).show()

    /**
     * 获取被选中的单选框(如果不添加点击事件,可以通过此函数获取被选中的单选框)
     */
    private fun getSelectedButton() = findViewById<RadioButton>(radioGroup.checkedRadioButtonId)
}

基础样例完整源代码

https://gitee.com/cxyzy1/RadioButtonDemo

常用属性说明

属性名用途
android:layout_width设置控件宽度,可设置为:match_parent(和父控件一样),wrap_content(按照内容自动伸缩),设置固定值(如200dp)
android:layout_height设置控件高度,可设置为:match_parent(和父控件一样),wrap_content(按照内容自动伸缩),设置固定值(如200dp)
android:gravity控件内对齐方式
android:background设置背景,可以是色值(如#FF0000)或图片等
android:visibility可选值: visible(显示), invisible(隐藏,但是仍占据UI空间),gone(隐藏,且不占UI空间)
android:checked是否选中,可选值:true(选中),false(未选中)

更多属性及实际效果,可以在开发工具里自行体验.