记录下实现过程,因为最近项目里要用到。我们都知道默认的RadioGroup+RadioButton是不能实现轻松换行的。如果每行使用一个RadioGroup来包裹RadioButton的话。其中的选择监听是个非常麻烦的事情。那么今天记录下RadioButton+GridLayout。
首先xml布局中添加一个GridLayout控件
<GridLayout
android:id="@+id/radioGridLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:columnCount="3"
android:rowCount="2"
android:padding="16dp"
android:alignmentMode="alignMargins"
android:columnOrderPreserved="false"
android:rowOrderPreserved="false">
</GridLayout>
接着在activity中,添加下面的代码就可以了。要几个就加几个,不一定单行得满,比如3+2个也可以,3+3个也可以。
private List<RadioButton> radioButtons = new ArrayList<>();//RadioButton集合
protected void onCreate(@Nullable Bundle savedInstanceState) {
setContentView(R.layout.xxxx);
//----------------------------要添加的代码,开始------------------------------------------
public final String[] options = {"a", "b", "c", "d", "e", "f"};//radiobutton的文字,假设有6个单选按钮
GridLayout radioGridLayout = findViewById(R.id.radioGridLayout);//拿到GridLayout 对象
// radioGridLayout.setColumnCount(3); // 设置列数为3,根据需要调整,这里也可以直接在xml里设置就行
// 假设我们有6个选项
// 第一行添加3个RadioButton
for (int i = 0; i < 3; i++) {
RadioButton radioButton = new RadioButton(this);
radioButton.setText(options[i]);
int radioButtonId = View.generateViewId();
radioButton.setId(radioButtonId);
radioGridLayout.addView(radioButton);
radioButtons.add(radioButton);
}
// 第二行添加3个RadioButton
for (int i = 0; i < 3; i++) {
RadioButton radioButton = new RadioButton(this);
radioButton.setText(options[i + 3]); // 假设从Option 4开始编号
int radioButtonId = View.generateViewId();
radioButton.setId(radioButtonId);
radioGridLayout.addView(radioButton);
radioButtons.add(radioButton);
}
//遍历所有的radiobutton,并为每个radiobutton设置单选事件
for (RadioButton radioButton : radioButtons) {
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
for (RadioButton rb : radioButtons) {//这里是为了遍历所有没有被选择的,把它们设置为false,实现单选效果
if (rb != buttonView) {
rb.setChecked(false);
}
}
//这里开始写你选择的监听事件
String str = radioButton.getText().toString();//获取当前的遍历radiobutton的文本
if (str.equals("a")) {
//如果选择的xxx按钮,就xxx
}
if (str.equals("b")) {
//如果选择的xxx按钮,就xxx
}
}
}
}
//----------------------------要添加的代码,结尾--------------------------------------------
}