android - 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”的左上角。
解决方案
您可以使用 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>
推荐阅读
- pandas - 如何拆分数据框中的字符串并将逗号作为分隔符
- c++ - 如何提高浮点二阶导数计算的精度?
- javascript - 如何在for循环中排除除一个之外的所有元素?
- c - glibc 使用内核函数
- reactjs - 材料 ui 文本字段类型日期,最小值不起作用
- javascript - Cant' access async nested json in state,得到“TypeError:无法读取未定义的属性'XX'”的错误
- c# - 仅将 SignalR 用于用户会话
- php - 如何停止暴力攻击以保护文件夹内的文档安全?
- ubuntu - 如何确保 Livenes/Readiness 探测使用 http 而不是 https 完成
- apache-kafka - 使用消息时的 Apache Kafka 清理