我很难获得视图,我正在膨胀以匹配父级宽度。我在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。目标是我膨胀的视图应该是用户屏幕的全宽。
非常感谢任何帮助!谢谢!!!
答案 0 :(得分:2)
如果Set Layoutparams不起作用,您可以尝试以下操作:
检查您是否动态设置了TableLayout的以下属性:
tableLayout.setStretchAllColumns(true);
答案 1 :(得分:1)
自己想出来。通过更改以下行
tr.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
改为
tr.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT, 1.0f));
并且一旦它被充气,它也会向视图添加相同的布局参数,它会根据需要延伸到匹配父级。