2011-06-03 92 views
7

我很奇怪,爲什麼出現這種情況:的Android的LinearLayout填充寬度

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="horizontal" android:layout_width="fill_parent" 
    android:gravity="center_vertical" 
    android:layout_height="wrap_content" android:layout_gravity="top" 
    android:background="@drawable/gradient" android:focusable="true" 
    android:paddingTop="5dip" android:paddingBottom="5dip" 
    android:focusableInTouchMode="true"> 
     <EditText android:id="@+id/searchField" 
      android:layout_width="wrap_content" android:layout_height="fill_parent" 

      android:paddingTop="2dip" android:paddingBottom="2dip" 
      android:paddingLeft="10dip" android:paddingRight="10dip" 
      android:inputType="textVisiblePassword" android:radius="5dip" 
      android:layout_marginLeft="10dip" 
      android:background="@drawable/search_background" android:textColor="#000000" /> 

     <Button android:id="@+id/info" android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_marginLeft="10dip" 
      android:background="@drawable/info_btn" /> 
</LinearLayout> 

如果我設置「FILL_PARENT」我的EditText的layout_width,需要家長的整個寬度和按鍵消失(我想這是隱藏在EditText下面)。

有人可以解釋我嗎?我想讓Button獲取自己的寬度,EditText獲取剩餘的寬度。

回答

21

您將EditText告訴fill_parent,因此它會填滿屏幕(整個寬度,不會留下按鈕空間)。

你想要的按鈕來包裝其內容與編輯文本,以填補剩餘部分,你可以做到這一點使用layout_weight屬性:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:layout_gravity="top" 
android:gravity="center_vertical" 
android:paddingTop="5dip" 
android:paddingBottom="5dip" 
android:orientation="horizontal"> 
<EditText 
    android:id="@+id/searchField" 
    android:layout_width="0dip" 
    android:layout_height="fill_parent" 
    android:layout_weight="1" 
    android:layout_marginLeft="10dip" 
    android:paddingTop="2dip" 
    android:paddingBottom="2dip" 
    android:paddingLeft="10dip" 
    android:paddingRight="10dip" 
    android:radius="5dip" 
    android:inputType="textVisiblePassword" 
    android:textColor="#000000" /> 
<Button 
    android:id="@+id/info" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_marginLeft="10dip" 
    android:text="Blah" /> 
</LinearLayout> 

(我把你繪製引用出來,以使它通用於其他人)

在一個側面不要讓你的XML外觀的整潔,在日食更易於維護的很好:

窗口>首選項> XML> XML文件>編輯

線寬120

分割多個屬性TICK

對齊最終托架勾去掉

保留空白標籤PCDATA勾去掉

清除所有空白行結束前不打鉤

插入空格TICK

點擊確定

然後你可以修復你的XML文件,當你打開一個XML文件時CTRL + A然後CTRL + SHIFT + F會很好地格式化它!

+1

非常感謝!缺少的屬性「layout_weight」+「0dip」寬度解決了所有問題。 – obo 2011-06-03 21:08:37

+0

也感謝我。 – 2012-01-31 13:11:03