layout_gravity无法在水平线性布局中工作

Ash*_*win 21 android android-linearlayout

我一直试图layout_gravity在横向使用linear layout.但它似乎没有用.我希望使用relative layout或任何其他布局.我想知道为什么它不与工作linear layout.我刚才使用layout_gravityvertical线性布局,它在我的预期的方式工作过.

<LinearLayout
    android:id="@+id/shata"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    >
    <TextView
        android:id="@+id/title_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="@color/black"
        android:text="shata1"
        android:textAppearance="?android:attr/textAppearanceMedium"
        />
    <TextView
        android:id="@+id/map_imageview"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="right"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="shata2"/>    
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,线性布局有一个orientation=horizontalwidth=match_parent(它只是在根布局内).但是,LinearLayout尽管我已经分别给出了它们layout_gravity=center,但两个TextView都显示在左侧layout_gravity=right.

Mat*_*lor 45

简短的回答:如果你有一个水平的LinearLayout,那么每个孩子只能有layout_gravitytop,bottomcenter.

这样做的原因是因为你已经告诉过LinearLayout要按照你指定的顺序从左到右水平对齐每个孩子,这意味着它只允许你在layout_gravity参数中指定每个孩子的垂直对齐方式,相反适用于LinearLayout垂直时.

有一个很好的链接解释各种重力如何在这里工作.

  • 一开始我什至也这么认为。但是根据这种逻辑,垂直LinearLayout应该只接受left,right和center的值。但是垂直布局也会对属性底部做出反应。 (2认同)

Tho*_*aud 6

作为Matt Taylor响应的补充,您可以使用layout_weight属性指定布局内元素的大小比例.有关详细信息,请参阅此主题.

上面的代码将水平空间分成三个等于的区域.

<LinearLayout
    android:id="@+id/shata"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <TextView
        android:layout_width="0"
        android:layout_height="match_parent"
        android:layout_weight="1"/>
    <TextView
        android:layout_width="0"
        android:layout_height="match_parent"
        android:layout_weight="1"/>
    <TextView
        android:layout_width="0"
        android:layout_height="match_parent"
        android:layout_weight="1"/>    
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

所以在这个例子中

  • 第一个元素看起来像 layout_gravity="left"
  • 第二个元素看起来像 layout_gravity="center"
  • 第三个元素看起来像 layout_gravity="right"