简体   繁体   中英

Clickable Text + Image using TextView in Android

How to put an clickable image in between string using a single TextView .

在此处输入图像描述

Using SpannableString , I am able to color part of string. But how to add a colored image? Any suggestion would be really appreciated.

This is not possible for a single TextView element. TextView s are not meant to contain images in the middle of them.

You can, however, add drawable resources to the top, right/start, left/end, or bottom of a given TextView by leveraging the drawableTop , drawableBottom , etc. attributes. But again, no way of adding an image in the middle of a TextView by using only one of them.

If you really want that specific effect, I would group a few XML components into any ViewGroup like a ConstraintLayout to get exactly what you want; eg

<androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/text_part_1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="first part of the text"
                android:textSize="16dp"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toStartOf="@id/image"/>

            <ImageView
                android:id="@+id/image"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:background="@color/white"
                app:layout_constraintStart_toStartOf="@id/text_part_1"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintEnd_toEndOf="@id/text_part_2"/>

            <TextView
                android:id="@+id/text_part_2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="first part of the text"
                android:textSize="16dp"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintStart_toEndOf="@id/image"/>
        </androidx.constraintlayout.widget.ConstraintLayout>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM