實測原生的RadioGroup只能控制其 直接子元件中的 RadioButton,
所以自己寫了一個RadioManager,這樣RadioButton就可以分散在布局任何角落了
RadioManager:
public class RadioButtonManager implements View.OnClickListener {
List<RadioButton> buttonList;
public RadioButtonManager(){
buttonList = new ArrayList<>();
}
public void addControlItem(RadioButton... radioButton){
for (RadioButton button : radioButton) {
buttonList.add(button);
}
addListener();
}
private void addListener() {
for (RadioButton radioButton : buttonList) {
radioButton.setOnClickListener(this);
}
}
public int getCheckedRadioButtonId(){
for (RadioButton radioButton : buttonList) {
if(radioButton.isChecked()){
return radioButton.getId();
}
}
return -1;
}
@Override
public void onClick(View v) {
RadioButton nowClickItem = (RadioButton) v;
for (RadioButton radioButton : buttonList) {
if(radioButton!=nowClickItem)radioButton.setChecked(false);
if(radioButton==nowClickItem)radioButton.setChecked(true);
}
}
}
用法:
radioButtonManager = new RadioButtonManager();
radioButtonManager.addControlItem(binding.radio1,binding.radio2);
int uiType;
int radioButtonId = radioButtonManager.getCheckedRadioButtonId();
if(radioButtonId==-1)return;
if(radioButtonId ==R.id.radio1) uiType=1;
if(radioButtonId ==R.id.radio2) uiType=2;
可置中的的radioButton樣式:
<RadioButton
android:id="@+id/radio1"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="@drawable/custom_radio_button_state"
android:button="@null"
android:foregroundGravity="center"
android:gravity="center"></RadioButton>
custom_radio_button_state:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 非點擊狀態 -->
<item android:state_checked="false" android:drawable="@drawable/icon_radio_not_select" />
<!-- 點擊狀態 -->
<item android:state_checked="true" android:drawable="@drawable/icon_radio_have_select" />
<!-- 默認狀態 -->
<item android:drawable="@drawable/icon_radio_not_select" />
</selector>