2011-09-19 85 views
1

對於我爲程序設計的頁面中的許多「標題」TextView,我希望它們是parent.Width/2,然後正確對齊。雖然在Java中編寫代碼相當容易,但我試圖儘可能地在XML佈局中進行操作,以避免XML-Java代碼交集,直到最後一點點(按下按鈕,完成頁面等)。android layout dynamic sizing

我是否需要瀏覽每個頁面並自己計算每個項目的特定寬度,或者是否有方法沿「fill_parent/2」行添加某些內容?

編輯:忘了提及什麼可能是一個關鍵的注意事項 - 我正在做的幾乎所有的事情都是在RelativeLayouts中,我對LinearLayouts在這個項目中的用處很少。

回答

4

如果你有一個的LinearLayout是左,右衝,你可以做到以下幾點:

<LinearLayout 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:weightSum="2" 
    android:gravity="left" 
    android:orientation="horizontal"> 
    <TextView 
     android:layout_weight="1" 
     android:layout_width="0dip" 
     android:layout_height="wrap_content" 
     android:text="I take up half the width!!!1" /> 
</LinearLayout> 

通過父設置weightSum,你說孩子的體重應該等於那個數量。通過將單個孩子的體重設置爲其一半,它將佔用一半的空間。確保將子項的寬度設置爲0,以便知道使用權重值計算其相對於其父項的空間。

然後,您可以通過在父LinearLayout上設置重力來對齊它。

+0

WeightSum只會影響「fill_parent」屬性嗎? –

+0

No. weightSum僅僅意味着「他們應該加起來多少」。所以,你的子元素將完全佔據他們的layout_weight /父母的weightSum *父母的實際寬度。防爆。 Layout = 400px,weightSum = 4,child = 1的layout_weight。子對象寬度爲100px(1/4 * 400 = 100) – Rich

0

使用兩列的tableview,其中每列被拉伸並具有文本視圖。然後隱藏第二TextView的

<TableLayout 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:stretchColumns="1"> 
    <TableRow> 
    <TextView android:id="@+id/textView" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text=" Set Item Name "/> 
    <TextView android:id="@+id/hiddenTextView" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:visibility="invisible"/> 
    </TableRow> 
</TableLayout>