欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > Android RadioButton+GridLayout实现多行多列的单选效果

Android RadioButton+GridLayout实现多行多列的单选效果

2025/4/19 7:51:04 来源:https://blog.csdn.net/qq_21004057/article/details/139583246  浏览:    关键词:Android RadioButton+GridLayout实现多行多列的单选效果

记录下实现过程,因为最近项目里要用到。我们都知道默认的RadioGroup+RadioButton是不能实现轻松换行的。如果每行使用一个RadioGroup来包裹RadioButton的话。其中的选择监听是个非常麻烦的事情。那么今天记录下RadioButton+GridLayout。

首先xml布局中添加一个GridLayout控件


<GridLayoutandroid: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个RadioButtonfor (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个RadioButtonfor (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() {@Overridepublic 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
}}}
}//----------------------------要添加的代码,结尾--------------------------------------------
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词