RadioGroup初步认识☞动态设置

本文介绍了在Java代码中如何动态设置RadioGroup的weight属性,如何动态添加RadioButton到RadioGroup,以及如何为RadioButton添加weight属性。示例代码展示了RadioGroup.LayoutParams的使用方法。

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

RadioGroup是Android中比较常用到的一个ViewGroup。所以,本文对于RadioGroup本身就不做过多介绍了,仅仅介绍一下如何在Java代码中动态设置属性以及动态添加RadioButton。

动态配置weight属性

RadioGroup作为LinearLayout的直接子类,当然可以设置weight属性,我们可以在代码中调用下面的方法来设置:

/**
     * Defines the desired weights sum. If unspecified the weights sum is computed
     * at layout time by adding the layout_weight of each child.
     *
     * This can be used for instance to give a single child 50% of the total
     * available space by giving it a layout_weight of 0.5 and setting the
     * weightSum to 1.0.
     *
     * @param weightSum a number greater than 0.0f, or a number lower than or equals
     *        to 0.0f if the weight sum should be computed from the children's
     *        layout_weight
     */
    @android.view.RemotableViewMethod
    public void setWeightSum(float weightSum) {
        mWeightSum = Math.max(0.0f, weightSum);
    }

例如这样:

RadioGroup radioGroup = new RadioGroup(this);
radioGroup.setWeightSum(3f);

动态添加RadioButton

当然,我们也可以使用Java代码动态添加RadioButton到RadioGroup中去,用的是下面这个从ViewGroup中继承的方法:

/**
 * Adds a child view. If no layout parameters are already set on the child, the
 * default parameters for this ViewGroup are set on the child.
 * 
 * <p><strong>Note:</strong> do not invoke this method from
 * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
 * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
 *
 * @param child the child view to add
 * @param index the position at which to add the child
 *
 * @see #generateDefaultLayoutParams()
 */
public void addView(View child, int index) {
   //省略部分代码 
}

例如这样:

RadioButton radioButton = new RadioButton(this);
radioButton.setText("Hello world!");
radioGroup.addView(radioButton);

给RadioButton添加weight属性

同时,我们也可以通过RadioGroup.LayoutParams这个内部类来为添加的RadioButton配置其与RadioGroup相关的属性,其中一个就是配合上面提到的weight属性。这么做有两种方式:

第一种:

RadioGroup.LayoutParams radioGroupLayoutParams = new RadioGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f);
radioButton.setLayoutParams(radioGroupLayoutParams);
radioGroup.addView(radioButton);

第二种:

RadioGroup.LayoutParams radioGroupLayoutParams = new RadioGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f);
radioGroup.addView(radioButton, radioGroupLayoutParams);

这两种方式都行,看自己喜好吧。不过RadioGroup.LayoutParams不光能配置weight属性,能够配置的属性多了去了,大家自己摸索吧。

完:)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值