'Change position of icon drawable in TextView

In my case, I have a textView with a drawable icon at the start of it(android:drawableStart), when the text of textView is multi-line, the icon goes in the vertical center of textView, but I want the icon to be aligned to the top of the text, how can I do this? I don't want use any other layouts for doing this

change_position_icon



Solution 1:[1]

There is api to set the drawable, but first you should set the bounds .

Solution 2:[2]

You can use setCompoundDrawablesWithIntrinsicBounds to set the drawable icons.

textview.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(getApplicationContext(), R.drawable.icon), null, ContextCompat.getDrawable(getApplicationContext(), R.drawable.icon_two), null);
                   

As according to the interface you can see the position clearly and use accordingly to your need.

public void setCompoundDrawablesWithIntrinsicBounds (int left, 
                int top, 
                int right, 
                int bottom)

Solution 3:[3]

It is something different but a quick workaround.
Just use a Checkbox instead of a TextView and use android:button to define your drawable:

<CheckBox
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:button="@drawable/..."
    android:gravity="top"
    android:clickable="false"
    android:text=".."/>

enter image description here

Solution 4:[4]

The approach I followed is to use SpannableString by setting a Span to the beginning of the string, being the Spain an ImageSpain

fun TextView.setDrawableAtStart(context: Context, textToSet: String?, @DrawableRes drawableRes: Int) {
if (textToSet.isNullOrBlank()) return

text = SpannableString(" $textToSet ").apply {
    val drawable = ContextCompat.getDrawable(context, drawableRes) ?: return
    drawable.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
    setSpan(
        ImageSpan(drawable, ImageSpan.ALIGN_BASELINE),
        0, // Start position
        1, // End position
        Spannable.SPAN_INCLUSIVE_EXCLUSIVE
    )
}

}

I encourage you to read this interesting article about styling a text in Android.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharman
Solution 2
Solution 3 Gabriele Mariotti
Solution 4 Javi