2010-04-27 47 views
6

我試圖得到像這樣的東西:http://img202.imageshack.us/img202/552/layoutoy.png。我將它用作列表項(在技術上作爲ExpandableListView的組視圖)。如何將按鈕對齊到右側,而不會被TextView重疊?

這裏的XML文件:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="horizontal" 
    android:layout_width="fill_parent" 
    android:layout_height="?android:attr/listPreferredItemHeight"> 

    <TextView 
     android:id="@+id/list_item_text" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:ellipsize="end" /> 

    <Button 
     android:id="@+id/list_item_button" 
     android:text="Click me!" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentRight="true" 
     android:layout_toRightOf="@id/list_item_text" /> 

</RelativeLayout> 

但是,這是行不通的。按鈕不包裝其內容,而是使用所有可用的水平空間。 TextView does包裝其內容,但我想要它做的是切斷它重疊的按鈕時。

換句話說,我希望所有按鈕的寬度相同,無論textviews中的文本數量多少。這是可能嗎?

回答

5

我想你應該嘗試一下。 使TextView位於按鈕的左側。這樣Textview將不會重疊按鈕。如果您希望在行尾處剪切它,則必須將其限制爲一行。目前它只是將文本的其餘部分移到下一行。

這應該做的伎倆:

<Button 
    android:id="@+id/list_item_button" 
    android:text="Click me!" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentRight="true"/> 

<TextView 
    android:id="@+id/list_item_text" 
    android:text="veryveryveryveryveryveryveryveryveryverylong" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_toLeftOf="@id/list_item_button" 
    android:ellipsize="end" /> 

</RelativeLayout> 
+0

這樣做的伎倆,歡呼! – benvd 2010-04-27 11:58:15

+0

+1。好想法! – Tiago 2013-09-11 00:08:24

4

之前有人試圖如上所示的方法(與RelativeLayout的),你應該使用的LinearLayout這一點。權重應正確設置:需要佔用空間的元素必須具有權重1和寬度設置爲fill_parent,需要保持其最小大小的元素必須具有權重0,寬度爲包裝內容。

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="horizontal" 
    android:layout_width="fill_parent" 
    android:layout_height="?android:attr/listPreferredItemHeight"> 
<TextView 
    android:id="@+id/list_item_text" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_weight=1 
    android:ellipsize="end" /> 

<Button 
    android:id="@+id/list_item_button" 
    android:text="Click me!" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_weight=0/> 

</LinearLayout> 
相關問題