如何在约束布局中将文本视图放置在 ImageVew 的顶部



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

但我无法在约束布局中找到此功能。

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

最新更新