English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Several methods to center layout in Android

In Android layout files, if you want a component (layout or View) to be centered within another layout (component), there are several methods to achieve this:

  1. android:layout_gravity
  2. android:gravity
  3. android:layout_centerInParent

layout_gravity

android:layout_gravity, used to specify the position of the current component (layout or View) within its parent component (layout). The parent layout should be a LinearLayout or its descendant.

The possible values of layout_gravity are:

  1. top
  2. bottom
  3. left
  4. right
  5. center_vertical
  6. fill_vertical
  7. center_horizontal
  8. fill_horizontal
  9. center
  10. fill
  11. clip_vertical
  12. clip_horizontal
  13. start
  14. end

The values related to centering have been bolded. The specific meanings of various values, see:

https://developer.android.com/reference/android/widget/LinearLayout.LayoutParams.html .

gravity

android:gravity is a property of View, used to specify the position of the child components of View. It is applicable to all Views and layouts. It has many values, for specific information, see: https://developer.android.com/reference/android/view/Gravity.html .

Values related to centering:

  1. center
  2. center_horizontal
  3. center_vertical

When you set a layout android:gravity="center", its child components will be centered. When you set a View android:gravity="center", its content will be centered, taking TextView as an example, the text will be centered.

layout_centerInParent

android:layout_centerInParent is a layout attribute of RelativeLayout. If the parent layout of a component (layout or View) is RelativeLayout, this attribute can be used to center. Its value is true or false.

Similar ones include:

  1. android:layout_centerHorizontal
  2. android:layout_centerVertical

For specific meaning and usage, see: https://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html .

This is the summary of several methods for centering the layout of Android, and more related information will be supplemented later, thank you for your support to this site!

Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously, and this website does not own the copyright, nor has it been manually edited, nor does it assume any relevant legal responsibility. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please report via email to codebox.com (replace # with @ when sending email) with relevant evidence. Once verified, this site will immediately delete the infringing content.