2012-01-17 23 views
2

我已經做了一個簡單的應用程序來說明我的問題。簡要說明: 該應用程序只包含一項活動。它的根視圖是TableLayout。後者充滿了TableRow元素,而這些元素又從「row.xml」中膨脹。這裏是代碼:RelativeLayout - > match_parent與父視圖的大小不一樣

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工具和檢查表中的行的寬度和相應的相對佈局 - I分別見320和0。如果我在相對佈局中聲明「match_parent」,它們爲什麼不相同(320和320)?我附上2張圖片,您可以在其中觀察您自己的元素寬度。

TableRow width RelativeLayout width

回答

1

你的問題是在這裏:row=(TableRow)inflater.inflate(R.layout.row, null, true);

你必須虛增您的行這樣的:

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

這樣的LayoutParams會得到你的XML文件加載。

+0

我試圖將該行更改爲「row =(TableRow)inflater.inflate(R.layout.row,table,false); 」,但hierarchyviewer仍顯示width = 0。然後我試着「row =(TableRow)inflater.inflate(R.layout.row,table,true);」並得到錯誤「java.lang.ClassCastException:android.widget.TableLayout不能轉換爲android.widget.TableRow 」 – 2012-01-18 08:54:51

+0

但是,你的TableLayout LauoutParams是什麼?我沒有看到你在代碼中將它們設置在哪裏。 – Cata 2012-01-18 08:57:50

+0

我以不同的方式做到了這一點:我從XML文件中刪除了TableRow標記,並將RelativeLayout附加到代碼中的行中。當我這樣做時,行寬爲320,相對佈局寬度爲317.這幾乎可以,但仍然很奇怪。 – 2012-01-18 08:59:53

1

這是因爲你的RelativeLayout不包含兒童及其onMeasure(..)方法尚未提供任何所需的寬度。

+0

如果我添加孩子,我的相對佈局的寬度變成等於最寬的孩子。但是,這仍然不是TableRow的寬度。爲什麼?我想要相對佈局match_parent。 – 2012-01-18 09:14:50

相關問題