RadioButton动态添加以及需要注意的问题

项目中有一个页面是顶部有一行菜单,且是不定数量的,当点击菜单项时更新内容区,第一个想到的就是向RadioGroup中动态添加RadioButton,这期间真是碰壁无数次,所幸现在终于弄好了,赶紧记录一下:

首先布局中弄一个RadioGroup当容器,然后动态创建RadioButton addView给RadioGroup,需要注意的是,由于容器是RadioGroup,所以它只能装RadioButton,且只能有一层,不能给RadioButton外层再加任何性的布局,否则直接崩掉。

RadioButton的动态创建可以有两种办法,第一就是xml,第二是new一个,如果是new一个的话,要让RadioButton有间隔需要setMargin(),然而xml也需要这样,到现在也没搞清楚到底是为啥,在xml中给RadioButton设置MarginLeft OR MarginRight都是隔不开的,所以只能setMargin(),因为我们用的容器是RadioGroup,所以为RadioButton设置LayoutParams也应该是RadioGroup.LayoutParams 。

由于菜单选中和未选中字体是两种颜色,所以我想让一进去到页面让菜单的第一项字体设置为选中颜色,可是我在for循环中判断是第一个然后给它设置setChecked(true)或者直接设置颜色,都是不行的,最后的解决办法是创建RadioButton用xml的方式,然后把RadioButton的样式写一个style引用,再在java代码中同样判断是第一个的时候,让RadioGroup.check(RadioButton.getId()),还有就是不知道如何获取我点击了哪一项,这个问题百度一下很快就解决了,为RadioButton设置setTag,然后在用的地方getTag就拿到了,这样问题就圆满的解决了,下面贴一下部分代码:

for (int i = 0 ; i < strMenu.length; i++){
    final RadioButton radioButton = (RadioButton) LayoutInflater.from(getActivity()).inflate(R.layout.item_topic_header_menu,null,false);
    radioButton.setText(strMenu[i]);
    RadioGroup.LayoutParams params_rb = new RadioGroup.LayoutParams(
            RadioGroup.LayoutParams.MATCH_PARENT,
            RadioGroup.LayoutParams.WRAP_CONTENT);
    params_rb.setMargins(20, 2, 20, 2);
    radioButton.setTag(i);
    parentlayout.addView(radioButton, params_rb);
    if(i == 0){
        parentlayout.check(radioButton.getId());
    }
    radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                ToastUtil.showShort(getActivity(), "你点击了" + radioButton.getTag());
            }
        }
    });
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值