2016-12-06 98 views
0

我有一個水平線性佈局,裏面有3個項目。如何在水平線性佈局中水平放置一個視圖

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal"> 

    <ImageButton 
     android:id="@+id/FirstItem" 
     android:layout_width="wrap_content" 
     android:layout_height="match_parent" 
     android:src="@drawable/ic_microphone" /> 

    <EditText 
     android:id="@+id/secondItem" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_weight="1" /> 

    <ImageButton 
     android:id="@+id/ThirdItem" 
     android:layout_width="wrap_content" 
     android:layout_height="match_parent" 
     android:layout_weight="0"/> 

</LinearLayout> 

在代碼中,我有時會隱藏第二個和第三個項目。我希望我的第一個項目在其他兩個隱藏的時候顯示在中間。

我該怎麼辦?目前,當我隱藏第二個和第三個項目時,第一個項目仍然停留在左側。我可以在第一個項目上設置layout_weight = 1,但當2和3是可見時,它不會正確顯示。

回答

1
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:gravity="center" 
    android:orientation="horizontal"> 

    <ImageButton 
     android:id="@+id/FirstItem" 
     android:layout_width="wrap_content" 
     android:layout_height="match_parent" 
     android:src="@drawable/ic_microphone" /> 

    <EditText 
     android:id="@+id/secondItem" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_weight="1" /> 

    <ImageButton 
     android:id="@+id/ThirdItem" 
     android:layout_width="wrap_content" 
     android:layout_height="match_parent" 
     android:layout_weight="0"/> 

</LinearLayout> 
1

在你的xml中使用android:gravityandroid:layout_gravity

android:gravity設置內容的嚴重性。

android:layout_gravity在其父項中設置佈局的重力。

編輯

使用android:gravity="center"在你的代碼會工作。

+0

我試了一下。似乎沒有工作。實際上是否可以在沒有填充整個寬度的情況下將項目水平放置在水平線性佈局中? – user1017674

+0

它最適合你嘗試兩種,你將學習使用哪種類型以及何時使用。在這裏,我們引導人們解決他們的問題並不能真正解決他們的問題。在你仍然找不到你的解決方案之後,我們來幫忙:) –

+0

實際上是否可以在不填充整個寬度的情況下水平居中放置在水平線性佈局中的物品? – user1017674