【发布时间】:2012-01-22 05:06:24
【问题描述】:
上下文: 我有一个 TableLayout(使用 XML 创建),它有一个 TableRow,它有一个 TextView。代码:
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:fillViewport="true"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TableLayout
android:id="@+id/mytable"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="1"
>
<TableRow>
<TextView
android:id="@+id/add_alarm"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:gravity="center"
android:text="New\nItem"
android:textSize="30sp"
/>
</TableRow>
</TableLayout>
</ScrollView>
在我的 Activity 的 onCreate() 方法中,我试图动态地向 TableRow 添加另一个视图。代码如下:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater inflater = LayoutInflater.from(this);
View mainLayout = inflater.inflate(R.layout.main, null);
TableLayout tl = (TableLayout) mainLayout.findViewById(R.id.mytable);
TableRow tr = (TableRow) tl.getChildAt(0);
Log.d(TAG, "tr class = " + tr.getClass().getName() + " | width = " + tr.getWidth() + "\n");
final RelativeLayout rl = (RelativeLayout) inflater.inflate(R.layout.alarm_widget, null);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1);
tr.addView(rl, lp);
tl.invalidate();
setContentView(mainLayout);
}
问题:这段代码没有达到预期的效果,即在等宽的列中显示两个视图(XML 布局中的一个,另一个动态添加的)。
- 使用上面给出的代码,动态添加的 View 的宽度为“0”,因此是不可见的。
- 如果我将代码更改为
tr.addView(rl)(即不参考 LayoutParams),动态添加的视图是可见的,但列的宽度不相等。
我怎样才能做到这一点?
编辑:我将基于 cmets 的代码更改为以下内容。它仍然无法按预期工作:
TableLayout.LayoutParams lp = new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT, 1f);
tr.addView(rl, lp);
【问题讨论】:
-
This question 与您的相似(接受的答案将是我推荐的答案 - 请注意 cmets)。