2013-07-12 103 views
3

我想在左側放置一個TextView,並在TextView的右側放置一個控件(例如CheckBox)。我希望控件在屏幕上左對齊。這並不難通過LinearLayout或RelativeLayout獲得。比如我這樣做與LinearLayout中:TextView將右側控件推出屏幕

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal" > 
    <TextView 
     android:id="@+id/todo_title" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textAppearance="@android:style/TextAppearance.Small" 
     android:maxLines="2" 
     android:textStyle="bold" /> 
    <View 
     android:layout_width="0dp" 
     android:layout_height="fill_parent" 
     android:layout_weight="1" /> 
    <CheckBox 
     android:id="@+id/todo_checkbox" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:enabled="false" 
     android:focusable="false"/> 
</LinearLayout> 

的問題是,當TextView的文本太長,它推動該複選框在屏幕和複選框不再可見。相反,我希望複選框固定在屏幕的右端,如果需要,TextView最終會分成兩行。 我該如何做到這一點?

+0

你有沒有試過玩'layout_weight'和'weightsum'? – chancea

回答

7

使用android:layout_weight="1"爲textview和複選框將始終在右側。檢查:Android Layout Weight

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal" > 
    <TextView 
     android:id="@+id/todo_title" 
     android:layout_width="0dp" 
     android:layout_height="wrap_content" 
     android:textAppearance="@android:style/TextAppearance.Small" 
     android:maxLines="2" 
     android:layout_weight="1" 
     android:textStyle="bold" /> 
    <CheckBox 
     android:id="@+id/todo_checkbox" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:enabled="false" 
     android:focusable="false"/> 
</LinearLayout> 
0

使用weightsumlayout_weight

Weightsum是賦予父母的值,表示所有兒童組件必須加起來才能達到總和。

Layout_weight給予該佈局的子項。該值對應於組件將佔用的佈局的數量。

<LinearLayout 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal" 
    android:weightsum = "100" > 
    <TextView 
     android:id="@+id/todo_title" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:textAppearance="@android:style/TextAppearance.Small" 
     android:maxLines="2" 
     android:layout_weight="30" 
     android:textStyle="bold" /> 
    <CheckBox 
     android:id="@+id/todo_checkbox" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:enabled="false" 
     android:layout_weight="70" 
     android:focusable="false"/> 

</LinearLayout> 

記住的值是反轉的(不知道它是如何工作),但最大layout_weight值佔據最小的面積。

+0

不適合我。 CheckBox僅部分顯示。 – user1781028

+0

玩弄layout_weight的值。它是否對所有值產生相同的結果? – Alexey