簡體   English   中英

如何在Android上集中自定義視圖?

[英]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 ,您可以將Viewlayout_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM