【发布时间】:2015-05-04 07:37:45
【问题描述】:
我很难获得我正在膨胀的视图以匹配父宽度。我在 Activity 的 setContentView 上使用的布局包含以下内容
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none" >
<TableLayout
android:id="@+id/tableRequestContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</TableLayout>
</ScrollView>
我正在膨胀的布局如下所示:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/layoutRequestItemContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="@color/Blue">
<TextView
android:id="@+id/RequestItemUnit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="1"
android:paddingLeft="10dp" />
<TextView
android:id="@+id/lblRequestItemCost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="1"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textSize="16sp" />
</LinearLayout>
然后在我的活动中,我循环遍历包含我的数据的 ArrayList,并在每次迭代时扩充视图,创建一个新的 TableRow,将视图添加到 TableRow,然后将 TableRow 添加到父表。我在下面使用的代码:
public class Requests extends Activity {
View view;
LayoutInflater inflater;
RequestData requestData;
TableLayout requestTable
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.request_layout);
requestTable = (TableLayout) findViewById(R.id.tableRequestContainer);
// HERE I POPULATE THE DATA OBJECT requestData with values
requestData = getRequestData();
for (int x=0; x<requestData.size(); x++) {
TableRow tr = new TableRow(this);
tr.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
view = LayoutInflater.from(this).inflate(R.layout.request_item_layout, tr, false);
// HERE IS THEN FIND THE TEXTVIEWS using view.findViewById(R...) and setText on each to the value in my data object. This works fine
// Add the view to the table row
tr.addView(view);
// Add the tablerow to the table
requestTable.addView(tr);
}
}
}
问题是视图正确膨胀并且我能够设置 TextViews 的值,但是容器使用 wrap_content 作为宽度而不是我在 XML 中指定的 match_parent。我不知道为什么并且一直在尝试我能想到的一切,但仍然无法让膨胀的视图将宽度拉伸到 match_parent。目标是我膨胀的视图应该是用户屏幕的整个宽度。
非常感谢任何帮助!谢谢!!!
【问题讨论】:
-
你不应该使用 TableRow.LayoutParams 吗?
-
@pskink - 我尝试使用 tr.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));也一样,但结果是一样的
标签: android android-layout tablelayout tablerow