android RadioGroup 默认是单行的,要多行只能用多个 RadioGroup, 然后自己控制各组互斥
radio.jpeg仅供参考
public class RadioInputPopup extends PopupWindow {
private static final int DEFAULT_COLS = 3; // 默认3列
private Context context;
private List<Item> items;
private RadioGroup[] radioGroups;
private OnRadioCheckedChanged onRadioCheckedChanged;
public RadioInputPopup(Context context, @NonNull List<Item> items, OnRadioCheckedChanged onRadioCheckedChanged) {
this.context = context;
this.items = items;
this.onRadioCheckedChanged = onRadioCheckedChanged;
setWidth(LinearLayout.LayoutParams.WRAP_CONTENT);
setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
setBackgroundDrawable(new ColorDrawable(context.getResources().getColor(android.R.color.white)));
setFocusable(true);
setTouchable(true);
setOutsideTouchable(true);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setLayoutParams(lp);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setPadding(20, 20, 20, 20);
setContentView(linearLayout);
int rows = (int) Math.ceil(items.size() / (double) DEFAULT_COLS);
radioGroups = new RadioGroup[rows];
for (int i = 0; i < rows; i++) {
RadioGroup radioGroup = new RadioGroup(context);
radioGroup.setTag("group" + i);
radioGroup.setOrientation(LinearLayout.HORIZONTAL);
radioGroup.setLayoutParams(lp);
radioGroup.setOnCheckedChangeListener(radioGroupOnCheckedChangeListener);
radioGroups[i] = radioGroup;
linearLayout.addView(radioGroup);
int j = DEFAULT_COLS;
if (i == rows - 1 && (items.size() % DEFAULT_COLS != 0)) {
j = items.size() % DEFAULT_COLS;
}
for (int k = 0; k < j; k++) {
RadioButton radioButton = new RadioButton(context);
radioButton.setOnCheckedChangeListener(radioButtonOnCheckedChangeListener);
radioButton.setTag(i * DEFAULT_COLS + k);
radioButton.setLayoutParams(lp);
radioButton.setText(items.get(i * DEFAULT_COLS + k).getText());
radioGroup.addView(radioButton);
}
}
}
private String lastCheckedGroupTag;
private RadioGroup.OnCheckedChangeListener radioGroupOnCheckedChangeListener = (group, checkedId) -> {
if (checkedId == -1) {
return;
}
String tag = group.getTag().toString();
if (lastCheckedGroupTag == null) {
lastCheckedGroupTag = tag;
return;
}
// 同组内选择
if (lastCheckedGroupTag.equals(tag)) {
return;
}
// 上组取消选择
int index = Integer.parseInt(lastCheckedGroupTag.substring("group".length()));
radioGroups[index].clearCheck();
lastCheckedGroupTag = tag;
};
private CompoundButton.OnCheckedChangeListener radioButtonOnCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked && onRadioCheckedChanged != null) {
int index = ((int) buttonView.getTag());
onRadioCheckedChanged.onRadioChecked(items.get(index).getValue());
}
}
};
public interface OnRadioCheckedChanged {
void onRadioChecked(String value);
}
}
网友评论