The magic of android:gravity="bottom center_horizontal"

  Today, in the java SE class, the teacher said logic or "|" means: if the condition on the left is true, the condition on the right will continue to be executed. For example:

int x=5;
if((x>1)|(x/0==1)){ //即使左侧的x>1成立,x/0也会继续执行,所以会抛异常
  reture ture;
} 

This reminds me of the common 

  android:gravity="bottom|center_horizontal"

It doesn't mean "or", but the same as logical or, both conditions must be executed. In this statement | does not mean or, but multiple choices. That is, the attribute of gravity can be selected multiple times. Gravity is a property of LinearLayout.

   For example, we often want to place buttons at the bottom and center in a vertical layout, as shown below:

If you don’t know that bottom and center_horizontal can be set at the same time, you can only set the width to full screen in LinearLayout, android:gravity="bottom", and then set android:layout_gravity="center_horizontal" in the button to achieve the effect. code show as below:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
     android:gravity="bottom"
    android:orientation="vertical" >
        <Button
            android:id="@+id/button1"
            android:layout_width="200dp"
            android:layout_height="100dp"
           android:layout_gravity="center_horizontal"
            android:textSize="30sp"
            android:text="确定" />
</LinearLayout>

 

However, if you know android:gravity="bottom|center_horizontal", it is much simpler , the code is as follows:

<?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="fill_parent"
    android:gravity="bottom|center_horizontal"
    android:orientation="vertical" >


    <Button
        android:id="@+id/button1"
        android:layout_width="200dp"
        android:layout_height="100dp"
        android:text="确定"
        android:textSize="30sp" />
</LinearLayout>

The layout_gravity similar to it can also be multi-selected. However, layout_gravity has limitations. If the orientation of LinearLayout is set to vertical, then only the left, right, and center_horizontal attributes in the layout_gravity of the Button will take effect in the horizontal direction, and the top, bottom, and center_vertical in the vertical direction will not work. It is impossible for us to select top|center_vertical at the same time. It is contradictory to be on top and vertically centered. Therefore, "|" in layout_gravity is hardly used. Compared with gravity, layout_gravity is limited.

Guess you like

Origin blog.csdn.net/zhangjin1120/article/details/52411898