首页 > 解决方案 > Android:如何将两个元素放在布局的中心,以便一个重叠另一个

问题描述

我有一个必须伸展以覆盖整个屏幕的布局。在里面我需要放置两个图像,两个图像都放置在布局的中心,这样第二个图像 - 恰好更小 - 与第二个图像重叠。

基本上它应该看起来像两个同心圆。

使用线性布局,我可以毫无问题地将其中一张图像居中。但由于我需要添加第二个重叠图像,因此我已切换到相对布局,但没有获得所需的结果:

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:layout_gravity="center"
    android:background="#ff0000">
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_centerHorizontal="true"
        android:background="#ffff00">
        
        <ImageView
            android:id="@+id/MyImageAtBackground"
            android:layout_width="200dp"
            android:layout_height="200dp"
            android:gravity="center"
            android:layout_gravity="center"
            android:src="@drawable/bigCircle" />
        <ImageView
            android:id="@+id/MyImageAtForeground"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:gravity="center"
            android:layout_gravity="center"
            android:src="@drawable/smallCircle" />
    </RelativeLayout>
</LinearLayout>

请注意,对于前一个 xml,“bigCircle”图像确实居中,但第二个 -“smallCircle” - 仍然位于“bigCircle”的左上角。

标签: androidandroid-layout

解决方案


您可以使用 ConstraintLayout 轻松完成此操作。较小的图像将根据较大的图像居中,如果您想移动较大的图像并且仍然使较小的图像居中。产生这个

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center">

    <ImageView
        android:id="@+id/MyImageAtBackground"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:background="#ff0000"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/MyImageAtForeground"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:background="#00FF00"
        app:layout_constraintBottom_toBottomOf="@+id/MyImageAtBackground"
        app:layout_constraintEnd_toEndOf="@+id/MyImageAtBackground"
        app:layout_constraintStart_toStartOf="@+id/MyImageAtBackground"
        app:layout_constraintTop_toTopOf="@+id/MyImageAtBackground" />
</androidx.constraintlayout.widget.ConstraintLayout>

推荐阅读