RadioGroup和CheckBox

本文详细介绍了Android开发中常用的UI控件RadioButton、RadioGroup及CheckBox的特性与使用方法,包括它们之间的区别、继承关系及实际应用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、RadioButton和CheckBox的区别:

1、单个RadioButton在选中后,通过点击无法变为未选中,单个CheckBox在选中后,通过点击可以变为未选中

2、一组RadioButton,只能同时选中一个,一组CheckBox,能同时选中多个

3、RadioButton在大部分UI框架中默认都以圆形表示
,CheckBox在大部分UI框架中默认都以矩形表示

二、RadioButton和RadioGroup的关系:

1、RadioButton表示单个圆形单选框,而RadioGroup是可以容纳多个RadioButton的容器

2、每个RadioGroup中的RadioButton同时只能有一个被选中

3、不同的RadioGroup中的RadioButton互不相干,即如果组A中有一个选中了,组B中依然可以有一个被选中

4、大部分场合下,一个RadioGroup中至少有2个RadioButton

5、大部分场合下,一个RadioGroup中的RadioButton默认会有一个被选中,并建议您将它放在RadioGroup中的起始位置

三、继承关系

RadioGroup

public class RadioGroup extends LinearLayout {}



public class LinearLayout extends ViewGroup {}



public abstract class ViewGroup extends View implements ViewParent, ViewManager {}

RadioButton

public class RadioButton extends CompoundButton {}

RadioGroup是线性布局管理器LinearLayout的子类,那么也就说明,在RadioGroup中的组件是线性排列的,也就是说RadioButton线性排列在RadioGroup内。RadioGroup可以视为是RadioButton的容器

CheckBox

public class CheckBox extends CompoundButton {}

其他


public abstract class CompoundButton extends Button implements Checkable {}

public class Button extends TextView {}

public class TextView extends View implements OnPreDrawListener {}

四、radiogroup和radiobutton使用举例:

XML文件中:

<RadioGroup
        android:id="@+id/radioGroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="性别">


        <RadioButton
            android:id="@+id/radioMale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="男"></RadioButton>


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

    </RadioGroup>

Java代码中:

//根据ID找到RadioGroup实例
        RadioGroup group = (RadioGroup) this.findViewById(R.id.radioGroup);
        //绑定一个匿名监听器
        group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup arg0, int arg1) {
                //获取变更后的选中项的ID
                int radioButtonId = arg0.getCheckedRadioButtonId();
                //根据ID获取RadioButton的实例
                RadioButton rb = (RadioButton) Act2.this.findViewById(radioButtonId);
                //更新文本内容,以符合选中项
                tv.setText("您的性别是:" + rb.getText());
            }
        });

注意:1、点击事件onCheckedChanged的第二个参数是:点中控件的布局id。2、radiogroup有addview方法,所以可以动态添加radiobutton

项目中常见radiogroup与fragment一起使用:

 //先初始化Fragment数据
    private void initData() {
        homeFragment = new HomeFragment();
        investFragment = new InvestFragment();
        meFragment = new MeFragment();
        moreFragment = new MoreFragment();
    }

     // 切换Fragment方法
    private void switchFragment(Fragment fragment) {
        FragmentManager manager = getSupportFragmentManager();

        manager.beginTransaction().replace(R.id.fl_main_container, fragment).commit();
    }


 //设置RadioGroup的点击事件的监听
    private void initLintener() {
        rgMain.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                Fragment fragment = null;

                switch (i) {
                    case R.id.rb_main_home:
                        fragment = homeFragment;
                        break;

                    case R.id.rb_main_invest:
                        fragment = investFragment;
                        break;

                    case R.id.rb_main_me:
                        fragment = meFragment;
                        break;

                    case R.id.rb_main_more:
                        fragment = moreFragment;
                        break;
                }

                // 切换Fragment方法
                switchFragment(fragment);
            }
        });

        // 默认选择会话页面
        rgMain.check(R.id.rb_main_home);
 } 

效果:单选,只能点击一次

五:CheckBox使用举例:

XML文件中:

<CheckBox
        android:id="@+id/cb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="false"
        android:text="已婚"/>

Checked属性是CheckBox最重要的属性之一,改变它的方式有三种:
1、XML中申明 2、代码动态改变 3、用户触摸
它的改变将会触发OnCheckedChange事件,而您可以对应的使用OnCheckedChangeListener监听器来监听这个事件。

Java代码中:

//获取CheckBox实例
        CheckBox cb = (CheckBox) this.findViewById(R.id.cb);
        //绑定监听器
        cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                Toast.makeText(Act2.this,
                        arg1 ? "选中了" : "取消了选中", Toast.LENGTH_LONG).show();
            }
        });

注意:1、点击事件onCheckedChanged的第二个参数是:是否选中。2、这个是否选中状态是:点击之后的状态

效果:可多选,可点击多次(选中-取消-选中的切换)

CheckBox自定义图片并自定义文字和图片的间距:

    android:background="@drawable/bg_2"
    android:button="@null"
    android:drawablePadding="5dp"
    android:drawableLeft="@drawable/selector1"

项目曾遇到:

1、listview的item中使用CheckBox,2、修改方块为圆形:

<CheckBox
        android:id="@+id/item_cb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="left|center_vertical"
        android:background="@drawable/expert_profession_selector"
        android:button="@null"
        android:clickable="false"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:gravity="center" />

1、设置了CheckBox没有焦点,这样的话,无法单独点击checkbox,而是在点击listview的条目后,Checkbox会响应操作。另外在item布局的根布局中添加android:descendantFocusability = “blocksDescendants”,通过此种方式也可解决ListView的item布局中含有CheckBox时所产生的焦点冲突问题。
2、checkbox可以使用文字,但项目中我没使用,修改方形
直接设置button为null,background设置圆形图片@drawable/expert_profession_selector,
当然也可直接设置button为@drawable/expert_profession_selector。

drawable/expert_profession_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/select_on" android:state_checked="true"></item>
    <item android:drawable="@drawable/select_on" android:state_selected="true"></item>
    <item android:drawable="@drawable/select_on" android:state_pressed="true"></item>
    <item android:drawable="@drawable/select_off"></item>

</selector>
//listview点击事件
lv_expert_skill.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {

// 取得ViewHolder对象,这样就省去了通过层层的findViewById去实例化我们需要的cb实例的步骤
                LvAdapter.ViewHolder holder = (LvAdapter.ViewHolder) view
                        .getTag();
                // 改变CheckBox的状态
                holder.item_cb.toggle();
                // 将CheckBox的选中状况记录下来
                adapter.getIsSelected().put(position,
                        holder.item_cb.isChecked());
            }
        });

使用一个HashMap

// 适配器
    class LvAdapter extends BaseAdapter {
        private List<String> list = new ArrayList<String>();
        // 用来控制CheckBox的选中状况
        private HashMap<Integer, Boolean> isSelected;
        private int isCheckedPos;

        public void setChecked(int isCheckedPos) {
            this.isCheckedPos = isCheckedPos;
        }

        public LvAdapter(List<String> list) {
            this.list = list;
            isSelected = new HashMap<Integer, Boolean>();

            // 初始化数据
            initData();
        }

        // 初始化isSelected的数据
        private void initData() {
            for (int i = 0; i < list.size(); i++) {
                getIsSelected().put(i, false);
            }
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder vHolder = null;
            if (convertView == null) {
                vHolder = new ViewHolder();
                convertView = LayoutInflater.from(parent.getContext()).inflate(
                        R.layout.choose_skill_profession_item, null);
                vHolder.textView = (TextView) convertView
                        .findViewById(R.id.item_choose_skill_name);
                vHolder.item_cb = (CheckBox) convertView
                        .findViewById(R.id.item_cb);

                convertView.setTag(vHolder);
            } else {
                vHolder = (ViewHolder) convertView.getTag();
            }

            // 设置UI
            vHolder.textView.setText(list.get(position));
            vHolder.item_cb.setChecked(getIsSelected().get(position));

            return convertView;
        }

        private HashMap<Integer, Boolean> getIsSelected() {
            return isSelected;
        }

        private void setIsSelected(HashMap<Integer, Boolean> isSelected) {
            this.isSelected = isSelected;
        }

        class ViewHolder {
            TextView textView;
            CheckBox item_cb;
        }

    }

参考:

Android控件系列之RadioButton&RadioGroup

【Android学习笔记】如何获取RadioGroup中RadioButton的值?

Android控件系列之CheckBox

实现listview中checkbox的多选与记录

android 下改变默认的checkbox的 选中 和被选中 图片

Android中ListView与CheckBox结合—-多选与记录

ListView和CheckBox的混乱问题

完美解决ListView和CheckBox焦点冲突及复用时CheckBox错位等一系列问题

推荐:

Android 必知必会 - RadioGroup 和 ViewPager 联动

checkbox 使用示例:

CheckBoxActivity:

/**
 * 参考:
 * http://blog.youkuaiyun.com/longyin88/article/details/53008117
 */

public class CheckBoxActivity extends AppCompatActivity {

    private CheckBox checkBox1;
    private CheckBox checkBox2;
    private CheckBox checkBox3;
    private TextView tv;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.checkbox_layout);

        checkBox1 = ((CheckBox) this.findViewById(R.id.checkbox1));
        checkBox2 = ((CheckBox) this.findViewById(R.id.checkbox2));
        checkBox3 = ((CheckBox) this.findViewById(R.id.checkbox3));
        tv = ((TextView) this.findViewById(R.id.tv));
    }

    /**
     * 全选
     */
    public void onClick1(View view) {
        boolean checked1 = checkBox1.isChecked();
        boolean checked2 = checkBox2.isChecked();
        boolean checked3 = checkBox3.isChecked();
        if (!checked1) {
            checkBox1.setChecked(true);
        }
        if (!checked2) {
            checkBox2.setChecked(true);
        }
        if (!checked3) {
            checkBox3.setChecked(true);
        }


    }

    /**
     * 反选
     */
    public void onClick2(View view) {
        boolean checked1 = checkBox1.isChecked();
        boolean checked2 = checkBox2.isChecked();
        boolean checked3 = checkBox3.isChecked();
        checkBox1.setChecked(!checked1);
        checkBox2.setChecked(!checked2);
        checkBox3.setChecked(!checked3);
    }

    /**
     * 全不选
     */
    public void onClick3(View view) {
        boolean checked1 = checkBox1.isChecked();
        boolean checked2 = checkBox2.isChecked();
        boolean checked3 = checkBox3.isChecked();
        if (checked1) {
            checkBox1.setChecked(false);
        }
        if (checked2) {
            checkBox2.setChecked(false);
        }
        if (checked3) {
            checkBox3.setChecked(false);
        }

    }
}

drawable/select_off:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

    <stroke
        android:width="2dp"
        android:color="@color/indigo" />
    <size
        android:width="15dp"
        android:height="15dp" />
</shape>

drawable/select_on:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

    <stroke
        android:width="2dp"
        android:color="#ff0000" />
    <size
        android:width="15dp"
        android:height="15dp" />
</shape>

drawable/cb_selector:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/select_on" android:state_checked="true" /><!--选中时效果-->
    <item android:drawable="@drawable/select_off" android:state_checked="false" /><!--未选中时效果-->
</selector>

checkbox_layout:

<?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:background="#e5e5e5"
    android:orientation="vertical">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="onClick1"
        android:text="全选" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="onClick2"
        android:text="反选" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="onClick3"
        android:text="全不选" />

    <View
        android:layout_width="match_parent"
        android:layout_height="15px"
        android:background="#ffffff" />

    <!--+++++++++++++ CheckBox                                +++++++++++-->
    <!--+++++++++++++ android:button="@drawable/cb_selector"  +++++++++++-->
    <!--+++++++++++++ 右侧文本 不可多布局  +++++++++++-->
    <CheckBox
        android:id="@+id/checkbox1"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:button="@drawable/cb_selector"
        android:gravity="center_vertical"
        android:paddingLeft="15dp"
        android:text="CheckBox button" />

    <View
        android:layout_width="match_parent"
        android:layout_height="15px"
        android:background="#ffffff" />

    <!--+++++++++++++ CheckBox                                +++++++++++-->
    <!--+++++++++++++ android:button="@null"                      +++++++++++-->
    <!--+++++++++++++ android:background="@drawable/cb_selector"  +++++++++++-->
    <!--+++++++++++++ 右侧文本 可多布局 【推荐这种写法】 +++++++++++-->

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <CheckBox
            android:id="@+id/checkbox2"
            android:layout_width="15dp"
            android:layout_height="15dp"
            android:background="@drawable/cb_selector"
            android:button="@null"
            android:gravity="center_vertical"
            android:paddingLeft="15dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="15dp"
            android:text="CheckBox button(null) background" />
    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="15px"
        android:background="#ffffff" />

    <!--+++++++++++++ CheckBox                        +++++++++++-->
    <!--+++++++++++++ android:button="@null"                        +++++++++++-->
    <!--+++++++++++++ android:drawableLeft="@drawable/cb_selector"  +++++++++++-->
    <CheckBox
        android:id="@+id/checkbox3"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:button="@null"
        android:checked="true"
        android:drawableLeft="@drawable/cb_selector"
        android:drawablePadding="15dp"
        android:gravity="center_vertical"
        android:text="CheckBox button(null) drawableLeft" />

    <!--+++++++++++++ TextView                                      +++++++++++-->
    <!--+++++++++++++ android:drawableLeft="@drawable/cb_selector"  +++++++++++-->
    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:drawableLeft="@drawable/select_on"
        android:drawablePadding="15dp"
        android:gravity="center_vertical"
        android:text="TextView drawableLeft" />

</LinearLayout>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值