<span style="font-family:SimHei;font-size:14px;"> RadioGroup myRadioGroup = new RadioGroup(this);
myRadioGroup.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
myRadioGroup.setOrientation(LinearLayout.HORIZONTAL);
for (int i = 0; i < 3; i++) {
RadioButton mRadioButton = new RadioButton(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
0, 100);
params.weight = 1.0f;
params.gravity = Gravity.CENTER;
mRadioButton.setLayoutParams(params);
mRadioButton.setText(""+i);
myRadioGroup.addView(mRadioButton);
}</span>
需求是創建3個橫向顯示的單選按鈕,並且這三個按鈕的寬度平分屏幕寬度,上面的寫法是錯誤的,設置的params屬性並不會有效果,因爲params中的一些屬性是相對於父佈局設置的,例如這個params.weight = 1.0f; 而此時這個單選按鈕並沒有一個父佈局,所以應該改成:
<span style="font-family:SimHei;font-size:14px;">for (int i = 0; i < 3; i++) {
RadioButton mRadioButton = new RadioButton(this);
myRadioGroup.addView(mRadioButton);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
0, 100);
params.weight = 1.0f;
params.gravity = Gravity.CENTER;
mRadioButton.setLayoutParams(params);
mRadioButton.setText(""+i);
}</span>