单选按钮多行

3

我想显示同一单选按钮组的6个单选按钮。但是这6个单选按钮仍然在同一行上,并且超出了屏幕。如何将它们显示在两行中(每行3个单选按钮)? 我已经尝试了我所能想到的所有方法(我是Android的新手)。


我尝试了我所能想到的一切。你尝试了什么?请解释一下。 - ariefbayu
@silent 我在RelativeLayout中放置了单选按钮以尝试leftOf/rightOf,但是按钮消失了。因为布局不允许在RadioGroup标记内出现。如果我将单选按钮分成两个不同的RadioGroup,则它们将不在同一组中。 尝试使用wrap content方法,但没有成功。 - Niraj Burde
3个回答

3
从搜索结果来看,似乎没有办法做到这一点,因为RadioGroup使用LinearLayout,它无法自动换行。由于单选按钮必须直接作为RadioGroup的子节点出现,因此您无法向RadioGroup添加子布局。
这意味着您需要手动实现此布局行为。有两个可能的选择:
  • 创建一个RadioGroup的副本,以扩展不同的布局,或至少允许您动态控制它。
  • 实现自己的自定义布局来替换RadioGroup,这个布局可以扩展您选择的布局,并实现OnClickListener。在这里有一个很好的例子here

感谢BD确认了我的结论,但是在我心里,我仍然有希望可能会有一些我忽略的东西。 同样也要感谢@silent。 - Niraj Burde

1
一个简单的解决方案是将您的RadioGroup包装在ScrollView中,这样用户就可以滚动到屏幕外的按钮(虽然不太优雅,但也不需要编写大量代码)。

对于第一个版本,我将使用这个简单的步骤。稍后我会创建自定义的无线电控制。谢谢。 - Niraj Burde

0

通过动态生成marginTop和marginLeft来调整需要在同一行的单选按钮。首先,获取屏幕宽度,将layoutparams marginLeft设置为屏幕宽度的一半,marginTop的高度需要根据具体的单选按钮进行调整。例如:

holder.question = (TextView) convertView.findViewById(R.id.topic_item_question);
            holder.option = (RadioGroup) convertView.findViewById(R.id.topic_item_option);
            holder.option1 = (RadioButton) convertView.findViewById(R.id.topic_item_option1);
            holder.option2 = (RadioButton) convertView.findViewById(R.id.topic_item_option2);

            //为了能够在一行显示两个radiobutton:获取屏幕的宽度
            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            int width = wm.getDefaultDisplay().getWidth();//左侧设置的间距
            int height = DensityDpToPx.dpToPx(context, 24);//处于第二个的高度间距

            LinearLayout.LayoutParams params = (LayoutParams) holder.option2.getLayoutParams();
            params.setMargins(width / 2, -height, 0, 0);
            holder.option2.setLayoutParams(params);

            holder.option3 = (RadioButton) convertView.findViewById(R.id.topic_item_option3);
            holder.option4 = (RadioButton) convertView.findViewById(R.id.topic_item_option4);

            LinearLayout.LayoutParams paramsTwo = (LayoutParams) holder.option4.getLayoutParams();
            paramsTwo.setMargins(width / 2, -height, 0, 0);
            holder.option4.setLayoutParams(paramsTwo);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接