在android中,如何将视图精确放置在其父视图/布局的中心上方

在android中,如何将视图精确放置在其父视图/布局的中心上方,android,Android,我想要实现的是,我想要将一个视图“放在”其父布局的中心之上。考虑下面的图像: 蓝色矩形显示了我希望查看的位置。正如您所看到的,它正好位于屏幕的(垂直)中心上方 挑战在于我们不知道视图的高度(因此我不能使用底部边距),我想在layoutxml文件中这样做(因此我不能使用代码来确定视图的高度并以编程方式将其设置为边距) 有了这些限制,有没有办法做到这一点?您可以按照以下布局将视图放置在所需位置- <?xml version="1.0" encoding="utf-8"?> <Re

我想要实现的是,我想要将一个
视图
“放在”其父布局的中心之上。考虑下面的图像:

蓝色矩形显示了我希望查看的
位置。正如您所看到的,它正好位于屏幕的(垂直)中心上方

挑战在于我们不知道视图的高度(因此我不能使用底部边距),我想在layout
xml
文件中这样做(因此我不能使用代码来确定视图的高度并以编程方式将其设置为边距)


有了这些限制,有没有办法做到这一点?

您可以按照以下布局将视图放置在所需位置-

<?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">

    <View android:id="@+id/dummy_view"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_centerInParent="true"
        />
    <View
        android:id="@+id/your_view"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_above="@+id/dummy_view"
        android:layout_centerHorizontal="true"
        />

</RelativeLayout>

我建议您使用
ConstraintLayout
,使用指南可以轻松完成(而不是使用视图作为定位点):

XML示例:

<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
    <android.support.constraint.Guideline
            android:id="@+id/mid_guideline"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintGuide_percent="0.5"
            />
    <View
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:background="#F00"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintBottom_toTopOf="@+id/mid_guideline"
            />
</android.support.constraint.ConstraintLayout>


这与“RelativeLayout技术”没有太大区别,后者将一个视图放在中间,另一个视图放在上面。我知道,这是一样的,但使用ConstraintLayout而不是RelativeLayout。我想是口味的问题吧。