[英]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.