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

3
我正在使用ConstraintLayout,想要将TextView放在ImageView之上。但是我无法在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下面。我该如何将文本放置在图像的顶部?翻译结果为:

在以上代码中,TextView被隐藏在ImageView下方。
如何将文本放置在图片上方?

3个回答

4
如果您的应用程序最低SDK版本为21或更高,则可以将此代码添加到任何UI元素,使其显示在其他元素之上:android:elevation="4dp"
不一定是4dp,可以根据项目需求调整高度。

1
如果您在XML中在ImageView下方添加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"


1

您也可以使用bringToFront()函数,该函数适用于API 21之前的版本:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接