[英]Android-How to center my custom View in LinearLayout?
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<com.example.root.howold.MyRing
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
我也嘗試設置gravity和layout_gravity ,但是它們實際上不起作用。
如何在布局中使MyRing(我的自定義視圖) 居中 ?
Try this:-
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.example.root.howold.MyRing
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
閱讀本文: Android上的Gravity和layout_gravity
要使視圖居中對齊,您可以:
LinearLayout case1:
“ android:gravity”適合兒童觀看。 如果這不起作用,請檢查其父視圖的寬度和高度。 並且,將父母的寬度和高度設置為更大的尺寸。
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TEST" />
</LinearLayout>
LinearLayout case2:
如果父視圖的空間為空,則“ android:layout_gravity”為其自身。
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="TEST" />
</LinearLayout>
的RelativeLayout
您可以將“ android:layout_centerInParent”用於RelativeLayout。
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="TEST" />
</RelativeLayout>
如果您使用根布局作為線性布局。 您可以在下面使用將自定義視圖設置為居中的文本。
根據您的要求可以使用
layout_gravity="center"
(要么)
layout_gravity="center_vertical"
(要么)
layout_gravity="center_horizontal"
以下是具有自定義視圖的xml。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Here you may some other views -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center">
<com.purpletalk.root.sampledemo.MyRing
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="hellooooo" />
</LinearLayout>
</LinearLayout>
如果您使用的是線性布局,
選項1:將android:gravity
添加到父視圖中,以使其所有子視圖居中
觀點。 例:
<LinearLayout
android:gravity="center">
<TextView/>
<TextView/> // Both these textviews will be aligned center
</LinearLayout>
選項2:如果您只想將一個子視圖居中,則將android:layout_gravity="center"
屬性添加到childview標記中。
<LinearLayout>
<TextView
android:layout_gravity="center" // Only this textview will be aligned center
/>
<TextView/>
</LinearLayout>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.