總結一下設置圖標的三種方式:
(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()) {
radioButton2.setTextColor(Color.parseColor("#FF0033"));
}else{
radioButton2.setTextColor(Color.parseColor("#000000"));
}
}
});
}
}
---------------------