Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
807 views
in Technique[技术] by (71.8m points)

android - layout_gravity not working in horizontal linear layout

I have been trying to use layout_gravity in a horizontal linear layout. But it doesn't seem to work. I don't want to use a relative layout or any other layout. I want to know why it is not working with linear layout.I have earlier used layout_gravity in vertical linear layouts and it has worked in the way I expected.

<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>

As you can see the the linear layout has a orientation=horizontal and width=match_parent(it is just inside the root layout). But both the TextViews are displayed sticking to the left of the LinearLayouteven though I have given their layout_gravity=center and layout_gravity=right respectively.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Short answer: If you have a horizontal LinearLayout, then each child can only have layout_gravity values of top, bottom, and center.

The reason for this is because you've already told the LinearLayout to align each child horizontally, left-to-right in the order you specify, which means that it only lets you specify the vertical alignment of each child in the layout_gravity parameter, and the opposite applies when your LinearLayout is vertical.

There's a good link explaining how the various gravities work here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...