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。

更多相关文章

  1. android用户界面-布局管理Layout
  2. Android 四大组件Broadcast
  3. Android基本组件之文本框与编辑框组件(自用)
  4. Android的五种布局
  5. Android RecyclerView 多布局与混排
  6. android基础入门布局讲解(2)

随机推荐

  1. Android 中ScrollView与ListView冲突问题
  2. Android(安卓)将Back 模拟或者转换为按Ho
  3. Android里用代码设置View的相关属性
  4. Android dependency 'com.android.suppor
  5. android 系统各种属性的获取
  6. android 控件的移动
  7. Android GLSurfaceView 透明
  8. Android跳转系统联系人界面插入联系人 传
  9. Android 版本及别名
  10. VideoView控件