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
属性,能够配置的属性多了去了,大家自己摸索吧。
完:)