Android布局居中的几种做法

Android的布局文件中,如果想让一个组件(布局或View)居中显示在另一个布局(组件)中,可以由这么几种做法:

  • android:layout_gravity
  • android:gravity
  • android:layout_centerInParent

layout_gravity

android:layout_gravity,用来指定当前组件(布局或View)在父组件(布局)中的位置,父布局应该是LinearLayout或者它的后裔。

layout_gravity取值可能是:

  • top
  • bottom
  • left
  • right
  • center_vertical
  • fill_vertical
  • center_horizontal
  • fill_horizontal
  • center
  • fill
  • clip_vertical
  • clip_horizontal
  • start
  • end

与居中相关的已经粗体标注出来。各种取值的具体含义,参看:https://developer.android.com/reference/android/widget/LinearLayout.LayoutParams.html

gravity

android:gravity是View的属性,用来指定View的子组件在View中的位置。适用于所有的View和布局。它的取值有很多,具体参见:https://developer.android.com/reference/android/view/Gravity.html

与居中相关的取值:

  • center
  • center_horizontal
  • center_vertical

当你设定一个布局android:gravity="center"时,它的子组件就会居中。当你设定一个Viewandroid:gravity="center"时,它的内容会居中,以TextView为例,文字会居中。

layout_centerInParent

android:layout_centerInParent是RelativeLayout的布局属性,如果一个组件(布局或View)的父布局是RelativeLayout,就可以使用这个属性来居中。其取值为 truefalse

与其类似的还有:

  • android:layout_centerHorizontal
  • android:layout_centerVertical

具体含义和用法参看:https://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html

原文地址:https://www.cnblogs.com/hehehaha/p/6147406.html