[关闭]
@linux1s1s 2019-02-14T10:43:50.000000Z 字数 1895 阅读 2738

Andrlid LinearLayout 布局居中

AndroidWidget 2015-06


如果你想实现这样的布局,两个按钮居中,该怎样做?

此处输入图片的描述

比较容易实现的是LinearLayout布局,当然如果换成RelativeLayout同样也可以实现。
这里简单说一下用RelativeLayout布局如何实现,首先需找中心点,然后以这个中心点为参照物即可实现。接下来看一下更容易实现的LinearLayout布局的实现。

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent"
  6. android:gravity="center">
  7. <Button
  8. android:layout_width="wrap_content"
  9. android:layout_height="wrap_content"
  10. android:id="@+id/start_server"
  11. android:text="Start" />
  12. <Button
  13. android:layout_width="wrap_content"
  14. android:layout_height="wrap_content"
  15. android:id="@+id/stop_server"
  16. android:text="Stop" />
  17. </LinearLayout>

如果现在需求改变了,中间只需要一个Button即可,那么实现起来很简单,只需要将上面的其中一个Button标签删除即可,但是有些人这么去实现

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent">
  6. <Button
  7. android:layout_width="wrap_content"
  8. android:layout_height="wrap_content"
  9. android:id="@+id/start_server"
  10. android:layout_gravity="center"
  11. android:text="Start" />
  12. </LinearLayout>

这么实现显然不能居中,虽然在Button标签指定了android:layout_gravity="center"但是貌似布局不领情,为啥?
原因很简单,LinearLayout只能有一个方向,要么Vertical,要么Horizontal,完全不会领layout_gravity这个属性的情,所以上面的实现只有这么一个结果

此处输入图片的描述

如果改成水平方向的布局

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="horizontal"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent">
  6. <Button
  7. android:layout_width="wrap_content"
  8. android:layout_height="wrap_content"
  9. android:id="@+id/start_server"
  10. android:layout_gravity="center"
  11. android:text="Start" />
  12. </LinearLayout>

会变成这样的结果

此处输入图片的描述

按照上面的理论也就能想通了,所以android:layout_gravity="center"这个属性虽然LinearLayout也具有,但是却虚晃一枪,真正其作用的还是其本身的属性android:gravity="center",当然如果想一探究竟,为啥不起作用,可以从LinearLayout这个布局的源代码看起,这里不再赘述。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注