如何在 ConstraintLayout 中将 TextView 放置在 ImageVew 之上

How to place a TextView on top of a ImageVew in ConstraintLayout

我正在使用 ConstraintLayout,我想在 ImageView 之上放置一个 TextView。

但我在 ConstraintLayout 中找不到此功能。

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.sayani.myApp.MainActivity">

<ImageView
    android:id="@+id/imageView"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginBottom="4dp"
    android:layout_marginEnd="4dp"
    android:layout_marginStart="4dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="1.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintVertical_bias="0.0"
    app:srcCompat="@drawable/image1" />

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="240dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    app:layout_constraintBottom_toBottomOf="@+id/imageView"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.501"
    app:layout_constraintStart_toStartOf="parent"/>
</android.support.constraint.ConstraintLayout>

在上面的代码中,TextView 隐藏在 ImageView 下。
如何将文字置于图片之上?

如果您的应用的最低 SDK 为 21 或更高,您可以将此添加到您想要显示在其他元素之上的任何 UI 元素:android:elevation="4dp"

不一定是 4dp,它可以更高或更低,具体取决于您项目中的工作。

您还可以使用 bringToFront() 函数,它适用于 pre-api 21:

TextView myTextView = findViewById(R.id.textView);
myTextView.bringToFront();

如果您在 XML 中将 TextView 添加到 ImageView 下方(就像您所做的那样),那么它 将出现在顶部 的 ImageView。因此,如果您在它出现在 ImageView 下方之前添加它。

<ImageView
    android:id="@+id/imageView"
    android:layout_width="200dp"
    android:layout_height="200dp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:srcCompat="@drawable/image1" />

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="@+id/imageView"
    app:layout_constraintBottom_toBottomOf="@+id/imageView"
    android:textSize="24sp"
    android:text="TextView on top of an ImageView" />

如果你想让它在屏幕上垂直居中,那么你可以使用

app:layout_constraintTop_toTopOf="@+id/imageView" app:layout_constraintBottom_toBottomOf="@+id/imageView"