Android中单选框RadioButton的基本用法

总结一下设置图标的三种方式:

(1)button属性:主要用于图标大小要求不高,间隔要求也不高的场合。

(2)background属性:主要用于能够以较大空间显示图标的场合。

(3)drawableLeft属性:主要用于对图标与文字之间的间隔有要求的场合。

注意使用 background 或者 drawableLeft时 要设置 android:button="@null"

监听:

radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {


}
});
1
2
3
4
5
6
7
下面是一个例子:
效果图:

布局文件: activity_radio_button.xml 中使用

<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:orientation="horizontal">

<RadioButton
android:id="@+id/radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:button="@null"
android:checked="true"
android:drawablePadding="10dp"
android:drawableTop="@drawable/selback"
android:gravity="center_horizontal"
android:text="男"
android:textColor="#FF0033"
/>

<RadioButton
android:id="@+id/radioButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:button="@null"
android:drawablePadding="10dp"
android:drawableTop="@drawable/selback"
android:gravity="center_horizontal"
android:text="女"
android:textColor="#000000"
/>

</RadioGroup>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
选择器:selback.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="@mipmap/on"/>
<item android:drawable="@mipmap/off"/>
</selector>
1
2
3
4
选择器用到的图片:

RadioButtonActivity 中监听选中

package rolechina.jremm.com.test4;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class RadioButtonActivity extends Activity {
private RadioGroup radioGroup;
private RadioButton radioButton1;
private RadioButton radioButton2;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio_button);
radioGroup = findViewById(R.id.radioGroup);
radioButton1 = findViewById(R.id.radioButton1);
radioButton2 = findViewById(R.id.radioButton2);

radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// 选中 文字 显示红色,没有选中显示黑色
if(radioButton1.isChecked()) {
radioButton1.setTextColor(Color.parseColor("#FF0033"));
}else{
radioButton1.setTextColor(Color.parseColor("#000000"));
}

if(radioButton2.isChecked(http://www.my516.com)) {
radioButton2.setTextColor(Color.parseColor("#FF0033"));
}else{
radioButton2.setTextColor(Color.parseColor("#000000"));
}


}
});
}
}

--------------------- 

猜你喜欢

转载自www.cnblogs.com/hyhy904/p/11069811.html