如何在Android上集中自定义视图?

tre*_*tas 9 layout android center view

我试图使用布局和重力属性将视图置于不同分辨率的中心,但它不起作用.有没有办法使自定义视图中心水平跨越不同的分辨率?

我需要在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>
Run Code Online (Sandbox Code Playgroud)

Ode*_*rik 1

假设您有一个View类似的内部布局FrameLayout,您可以将View's设置layout_gravitycenter。不要把它与 混为一谈gravity

另外,可能确实需要重写 onMeasure()。阅读它的文档来决定是否需要覆盖它。如果这样做,请注意参数是用View.MeasureSpec.