希望通过 LOOP 或动态TextView Genrate在此子LinearLayout中实现此布局 android:layout_weight =" 0.5"
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/child_layout"
android:orientation="horizontal">
<TextView
android:id="@+id/text_range_min"
style="@android:style/TextAppearance.Small"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="100px"
android:layout_weight="0.5"
android:gravity="left"
android:text="1" />
<TextView
android:id="@+id/text_range_min2"
style="@android:style/TextAppearance.Small"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:gravity="left"
android:text="2" />
<TextView
android:id="@+id/text_range_min3"
style="@android:style/TextAppearance.Small"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:gravity="left"
android:text="" />
<TextView
android:id="@+id/text_range_min4"
style="@android:style/TextAppearance.Small"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:gravity="left"
android:text="3" />
<TextView
android:id="@+id/text_range_max"
style="@android:style/TextAppearance.Small"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:gravity="right"
android:text="4" />
</LinearLayout>
它可能有更多或更少的文本视图所以我想通过循环动态添加,并为所有文本视图分配权重
我正在使用它但不会设置重量
LinearLayout MainLL= (LinearLayout) findViewById(R.id.child_layout);
for(int i=0; i<5; i++){
TextView text = new TextView(this);
text.setText(""+i); // <-- does it really compile without the + sign?
text.setGravity(Gravity.LEFT);
text.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT,0.5f));
MainLL.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
MainLL.addView(text);
}
答案 0 :(得分:0)
更改为代码中的text.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 0.5f));
。
TextView
0
TextView
0.5f
试试这个。
LinearLayout MainLL = (LinearLayout) findViewById(R.id.child_layout);
for (int i = 0; i < 5; i++) {
TextView text = new TextView(this);
text.setText("" + i);
text.setGravity(Gravity.LEFT);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 0.5f);
// add margin
layoutParams.setMargins(10,10,10,10);
text.setLayoutParams(layoutParams);
MainLL.addView(text);
}