2016-12-06 96 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