我做了一个简单的应用程序来说明我的问题。简要说明:
该应用程序仅包含一项活动。它的根视图是TableLayout。后者填充有TableRow元素,这些元素又从“ row.xml”扩展而来。这是代码:

TestActivity.java

public class TestActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    LayoutInflater inflater=getLayoutInflater();
    TableLayout table=new TableLayout(this);
    setContentView(table);
    TableRow row;
    for(int i=0;i<3;i++){
        row=(TableRow)inflater.inflate(R.layout.row, null, true);
        table.addView(row);
    }

  }
}


在row.xml中,TableRow是根元素,它具有一个子级-RelativeLayout。请注意RelativeLayout的属性android:layout_width =“ match_parent”。
row.xml:

<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/background"
>

<RelativeLayout
    android:id="@+id/announcement_row_relative_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
     >
</RelativeLayout>




然后,我运行项目,打开hierarchyViewer工具并检查表行的宽度和相应的相对布局-我分别看到320和0。如果在相对布局中声明“ match_parent”,为什么它们不相同(320和320)?我附加了2张图像,您可以在其中观察自己的元素的宽度。

最佳答案

您的问题在这里:row=(TableRow)inflater.inflate(R.layout.row, null, true);

您必须像这样使行膨胀:

row=(TableRow)inflater.inflate(R.layout.row, table, false);


这样,将从您的XML文件中加载LayoutParams

07-24 09:48
查看更多