Android如何在RadioGroup中动态创建内部元素对齐的LinearLayout
问题解决
你漏掉了3个核心配置:
LinearLayout默认是垂直方向布局,需要显式设置为水平方向,才能让三个TextView横向排列- 使用
layout_weight分配宽度时,对应方向的尺寸参数要设置为0dp,而不是WRAP_CONTENT或者MATCH_PARENT,否则weight属性不会按预期分配空间 - 需要给
TextView设置居中对齐的gravity属性,才能让文字在分配的宽度区域内居中显示,另外作为RadioGroup的直接子元素,LinearLayout需要设置RadioGroup.LayoutParams类型的布局参数才能正确适配RadioGroup的布局规则
修正后的代码如下:
// 1. 先创建LinearLayout,显式设置水平方向 final LinearLayout linearLayout = new LinearLayout(this); linearLayout.setOrientation(LinearLayout.HORIZONTAL); // 给LinearLayout设置适配RadioGroup的布局参数,宽度撑满父容器 RadioGroup.LayoutParams llParams = new RadioGroup.LayoutParams( RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.WRAP_CONTENT ); linearLayout.setLayoutParams(llParams); // 2. TextView的布局参数,宽度设为0dp配合weight分配 LinearLayout.LayoutParams param = new LinearLayout.LayoutParams( 0, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f); final TextView text1 = new TextView(this); text1.setText("aaa"); // 3. 设置文字居中 text1.setGravity(Gravity.CENTER); text1.setLayoutParams(param); linearLayout.addView(text1); final TextView text2 = new TextView(this); text2.setText("bbb"); text2.setGravity(Gravity.CENTER); text2.setLayoutParams(param); linearLayout.addView(text2); final TextView text3 = new TextView(this); text3.setText("ccc"); text3.setGravity(Gravity.CENTER); text3.setLayoutParams(param); linearLayout.addView(text3); radioGroup.addView(linearLayout);
内容的提问来源于stack exchange,提问作者Vadim
相关产品推荐
相关产品推荐

