RadioButton,就是一个单选按钮,Radioroup包含一组RadioButton,供选择,这里只能单选,并且选中后再次点击不会取消选中。
常用属性:
android:checked="true" 设置 是否为选中状态
android:text="@string/title1_button2" 设置单选的文字内容
android:layout_marginLeft="30dp" 控制两个单选按钮之间的距离
android:paddingLeft="20dp" 控制单选按钮和文字之间的距离
android:button="@drawable/radio" 设置单选按钮的点击效果
布局文件如下:
<RadioGroup
android:id="@+id/title1_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginLeft="10dp">
<RadioButton
android:id="@+id/title1_button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/title1_button1"
android:textColor="@color/description_text_color"
android:button="@drawable/radio"
android:paddingLeft="20dp"
android:textSize="@dimen/title_text_size"
/>
<RadioButton
android:id="@+id/title1_button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/title1_button2"
android:textColor="@color/description_text_color"
android:textSize="@dimen/title_text_size"
android:button="@drawable/radio"
android:paddingLeft="20dp"
android:layout_marginLeft="30dp" 设置和上一个单选按钮的左边距离30dp
/>
</RadioGroup>
在代码中添加方式如下:
RadioButton radioBtn1, radioBtn2;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
params.gravity = Gravity.CENTER_VERTICAL;
RadioGroup radioGroup = new RadioGroup(this);
radioGroup.setLayoutParams(params);
radioGroup.setOrientation(RadioGroup.HORIZONTAL);
radioBtn1 = new RadioButton(this);
// 界面布局宽度,高度
LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
radioBtn1.setLayoutParams(lp1);
radioBtn1.setText("按钮1");
radioBtn1.setTextColor(Color.parseColor("#999d9c"));
radioGroup.addView(radioBtn1);
radioBtn2 = new RadioButton(this);
LinearLayout.LayoutParams lp2= new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
radioBtn2.setLayoutParams(lp2);
radioBtn2.setTextColor(Color.parseColor("#999d9c")); radioBtn2.setText("按钮2"); radioGroup.addView(radioBtn2);
设置RadioGroup的监听
title1_group = (RadioGroup) findViewById(R.id.title1_group);
title1_group.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
title1_group_isSelected = true;
if (checkedId == R.id.title1_button1) {
title1_group_selected = 0;
} else if (checkedId == R.id.title1_button2) {
title1_group_selected = 1;
}
}
});