[英]How to center a Custom View on Android?
我試圖使用布局和重力屬性將視圖置於不同分辨率的中心,但它不起作用。 有沒有辦法使自定義視圖中心水平跨越不同的分辨率?
我需要在onMeasure方法上做點什么嗎?
這是我現在正在嘗試的事情之一,視圖位於中心的左側..
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="50dp"
android:gravity="center_horizontal">
<com.application.app.ui.CustomView
android:id="@+id/ivCoinAnimation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/>
</RelativeLayout>
</FrameLayout>
假設您在FrameLayout
類的布局中有一個View
,您可以將View
的layout_gravity
設置為center
。 不要與gravity
混合!
此外,可能確實需要覆蓋onMeasure()。 閱讀它的文檔,以決定是否需要覆蓋它。 如果這樣做,請注意參數是使用View.MeasureSpec
編碼的。
您應該在自定義View類中實現
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
在其中,您應該計算自定義視圖的高度和寬度。 如果您需要在父布局中集中自定義視圖 - 請確保:
AND / OR
例如:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
final int height = mCircleRadius * 2; //calculated
final int width = getMeasuredWidth(); //parent width
setMeasuredDimension(width, height);
}
現在,您可以使用next作為自定義視圖:
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
PS你看到android:layout_centerHorizontal="true"
沒有效果。 原因是在onMeasure中使用父寬度而不是計算精確寬度。
以下是如何將兩個按鈕置於屏幕中心的示例。 這也適用於您的CustomView。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<Button android:text="Button" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<Button android:text="Button" android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>
</LinearLayout>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.