NRUSINGHA MOHARANA
NRUSINGHA MOHARANA

Reputation: 1559

Clickable Text + Image using TextView in Android

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

enter image description here

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

Upvotes: 0

Views: 119

Answers (1)

Iván Garza Bermea
Iván Garza Bermea

Reputation: 742

This is not possible for a single TextView element. TextViews 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; e.g.

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

Upvotes: 1

Related Questions