Android 程式碼中動態為RadioGroup新增RadioButton
阿新 • • 發佈:2018-12-31
在程式碼中new出RadioButton,並new出佈局引數LayoutParams,通過layoutParams為radioButton設定margin值,再為radioButton設定其他屬性即可。
RadioButton radioButton = new RadioButton(this); RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT,50); layoutParams.setMargins(10, 10, 10, 10); radioButton.setLayoutParams(layoutParams); radioButton.setText("rb1"); radioButton.setTextSize(12); radioButton.setButtonDrawable(android.R.color.transparent);//隱藏單選圓形按鈕 radioButton.setGravity(Gravity.CENTER); radioButton.setPadding(10, 10, 10, 10); radioButton.setTextColor(getResources().getColorStateList(R.color.selector_white_graydark_checked));//設定選中/未選中的文字顏色 radioButton.setBackground(getResources().getDrawable(R.drawable.selector_radiobtn_bg));//設定按鈕選中/未選中的背景 group.addView(radioButton);//將單選按鈕新增到RadioGroup中
注:RadioButton是RadioGroup的直接子View,使用的佈局引數必須是RadioGroup.LayoutParams。