Context:我有一个 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),动态添加的视图是可见的,但列的宽度不相等。
我怎样才能实现这个目标?
Edit:我根据评论将代码更改为以下内容。它仍然没有按预期工作:
TableLayout.LayoutParams lp = new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT, 1f);
tr.addView(rl, lp);