首页 > 解决方案 > How to Overlay text over image at left top corner

问题描述

I want to have textview over image at top left corner of the Imageview similar to this. how can I do this. enter image description here

I have this code but It doesn't do what i want.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/myImageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/myImageSouce"
        android:scaleType="centerCrop"/>

    <TextView
        android:id="@+id/myImageViewText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="@dimen/spacing_medium"
        android:layout_gravity="center"
        tools:text="Test"/>
</FrameLayout>

Thanks for help in advance.

标签: javaandroidxmlandroid-layout

解决方案


Try using a ConstraintLayout. Here's a simple example. For layering, views are layered in the order listed in the xml so if you want the TextView in front put it last in the xml

<?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=".MainActivity">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        app:srcCompat="@drawable/ic_home_black_24dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Some Words"
        android:padding="20dp"
        android:background="#00ff00"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Android Studio Preview


推荐阅读