21

I know how to underline text in a textview. But how to underline text with some different color ? Underline can be done with:

TextView t = (TextView) findViewById(R.id.textview);
t.setPaintFlags(t.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
t.setText("Underline Text");

Let say my textcolor is black and I want to underline the same with blue color, how to do it ? Thanks in advance.

3
  • I am afraid you need two textviews for that!
    – dd619
    Sep 27, 2013 at 8:57
  • You can use like this Email.setText(Html.fromHtml("W : "+"<u><FONT COLOR=\"#80776b\" >"+Email1+"</Font></u>")); Use color code what you want.
    – khubaib
    Sep 27, 2013 at 9:04
  • ~Vipul J, did you overcome this problem?
    – Dolly Rosy
    Jan 22, 2019 at 5:46

10 Answers 10

24

I had the same problem and I have stumbled upon Layout class when reading some other posts for doing this on EditText. It provides everything you need to make this happen by manually drawing underline with canvas.

First I defined custom attributes for an easy customization in XML layout files

<declare-styleable name="UnderlinedTextView" >
    <attr name="underlineHeight" format="dimension" />
    <attr name="underlineOffset" format="dimension" />
    <attr name="underlineColor" format="color" />
    <attr name="underLinePosition" format="enum">
        <enum name="baseline" value="0" />
        <enum name="below" value="1" />
    </attr>
</declare-styleable>

And a custom TextView class

   class UnderlinedTextView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : androidx.appcompat.widget.AppCompatTextView(context, attrs, defStyleAttr) {

    @Retention(AnnotationRetention.SOURCE)
    @IntDef(POSITION_BASELINE, POSITION_BELOW)
    annotation class UnderLinePosition {
        companion object {
            const val POSITION_BASELINE = 0
            const val POSITION_BELOW = 1
        }
    }

    private val linePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.FILL
    }

    var lineColor: Int
        get() = linePaint.color
        set(value) {
            if (linePaint.color != value) {
                linePaint.color = value
                invalidate()
            }
        }

    var lineHeight: Float
        get() = linePaint.strokeWidth
        set(value) {
            if (linePaint.strokeWidth != value) {
                linePaint.strokeWidth = value
                updateSpacing()
            }
        }

    var lineTopOffset = 0F
        set(value) {
            if (field != value) {
                field = value
                updateSpacing()
            }
        }

    @UnderLinePosition
    var linePosition = POSITION_BASELINE

    private val rect = Rect()

    private var internalAdd: Float = lineSpacingExtra

    private inline val extraSpace
        get() = lineTopOffset + lineHeight

    init {
        val density = context.resources.displayMetrics.density

        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.UnderlinedTextView, defStyleAttr, 0)
        lineColor = typedArray.getColor(R.styleable.UnderlinedTextView_underlineColor, currentTextColor)
        lineTopOffset = typedArray.getDimension(R.styleable.UnderlinedTextView_underlineOffset, 0f)
        lineHeight = typedArray.getDimension(R.styleable.UnderlinedTextView_underlineHeight, density * 1)
        linePosition = typedArray.getInt(R.styleable.UnderlinedTextView_underLinePosition, POSITION_BASELINE)
        typedArray.recycle()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        setMeasuredDimension(measuredWidth, measuredHeight + (extraSpace + 0.5f).toInt())
    }

    override fun onDraw(canvas: Canvas?) {
        canvas?.takeIf { !text.isNullOrEmpty() }?.let {
            val count = lineCount
            val layout = layout
            var xStart: Float
            var xStop: Float
            var yStart: Float
            var firstCharInLine: Int
            var lastCharInLine: Int
            var lastLine: Boolean
            var offset: Int
            val lineSpacing = lineSpacingExtra * lineSpacingMultiplier
            for (i in 0 until count) {
                val baseline = getLineBounds(i, rect)
                lastLine = i == count - 1
                offset = if (lastLine) 0 else 1
                firstCharInLine = layout.getLineStart(i)
                lastCharInLine = layout.getLineEnd(i)
                xStart = layout.getPrimaryHorizontal(firstCharInLine)
                xStop = layout.getPrimaryHorizontal(lastCharInLine - offset)
                yStart = when (linePosition) {
                    POSITION_BASELINE -> baseline + lineTopOffset
                    POSITION_BELOW -> (rect.bottom + lineTopOffset) - if (lastLine) 0F else lineSpacing
                    else -> throw NotImplementedError("")
                }
                canvas.drawRect(xStart, yStart, xStop, yStart + lineHeight, linePaint)
            }
        }
        super.onDraw(canvas)
    }

    private fun updateSpacing() {
        setLineSpacing(internalAdd, 1f)
    }

    override fun setLineSpacing(add: Float, mult: Float) {
        internalAdd = add
        super.setLineSpacing(add + extraSpace, 1f)
    }
}

Then it's usage is simple

<some.package.UnderlinedTextView
    android:id="@+id/tvTest"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="10dp"
    android:layout_marginLeft="20dp"
    android:layout_marginRight="20dp"
    android:gravity="center"
    android:text="This is a demo text"
    android:textSize="16sp"
    app:underlineColor="#ffc112ef"
    app:underlineHeight="3dp"/>

Final result

  • Multi line

    enter image description here
  • Single line

    enter image description here
3
  • how can i underline only a specific text with this custom view, without spannable and else....
    – Reprator
    Aug 22, 2017 at 18:24
  • I think you have a crash on this UnderlinedTextView class, in case the text is empty. As a workaround, I think it's fine to add a check about the text on onDraw : if (text.isNullOrEmpty()) { super.onDraw(canvas) return } Nov 19, 2018 at 7:52
  • Saved my a** when our designer gave me some custom fonts that would only render an extremely thin line when using an UnderlineSpan. Thanks!
    – dell116
    Jun 24, 2019 at 14:13
5

Another solution, this time without extending TextView (based on a question I wrote a long time ago, here) :

Have a drawable to be shown as the underline, and have a span for the text itself :

text_underline.xml

<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="line">
    <padding android:bottom="10dp"/>
    <stroke
        android:width="1dp"
        android:color="#3792e5"/>
</shape>

DrawableSpan.kt

class DrawableSpan(private val drawable: Drawable) : ReplacementSpan() {
    private val padding: Rect = Rect()

    init {
        drawable.getPadding(padding)
    }

    override fun draw(canvas: Canvas, text: CharSequence, start: Int, end: Int, x: Float, top: Int, y: Int, bottom: Int, paint: Paint) {
        val rect = RectF(x, top.toFloat(), x + measureText(paint, text, start, end), bottom.toFloat())
        drawable.setBounds(rect.left.toInt() - padding.left, rect.top.toInt() - padding.top, rect.right.toInt() + padding.right, rect.bottom.toInt() + padding.bottom)
        canvas.drawText(text, start, end, x, y.toFloat(), paint)
        drawable.draw(canvas)
    }

    override fun getSize(paint: Paint, text: CharSequence, start: Int, end: Int, fm: Paint.FontMetricsInt?): Int = Math.round(paint.measureText(text, start, end))

    private fun measureText(paint: Paint, text: CharSequence, start: Int, end: Int): Float = paint.measureText(text, start, end)

}

usage:

    val text = getString(R.string.large_text)
    val spannable = SpannableString(text)
    spannable.setSpan(DrawableSpan(resources.getDrawable(R.drawable.text_underline)), 0, text.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    textView.setText(spannable, TextView.BufferType.SPANNABLE)

And the result:

enter image description here

4

If you are an XML's fan. Take a look at my solution:

Create a selector selector_edittext_white.xml in drawable folder

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:bottom="-15dp">
    <rotate xmlns:android="http://schemas.android.com/apk/res/android"
        android:fromDegrees="0"
        android:pivotX="0.5"
        android:pivotY="0.5"
        android:toDegrees="0">
        <shape android:shape="line">
            <stroke
                android:width="0.5dp"
                android:color="@android:color/white" />
        </shape>
    </rotate>
  </item>
</layer-list>

Then, set your EditText

android:background="@drawable/selector_edittext_white"

In the setting above, the underline's color is white, and you can move it by changing android:bottom above is "-15dp" . In case it's disappear, try to set your EditText bottom margin like this

android:layout_marginBottom="5dp"
2
  • This is a quite nice solution for single-lined text, but it does not work if the text is multi-lined.
    – Ecthelion
    Oct 24, 2020 at 12:08
  • Nice solution for a single line text. Used in android.widget.Button, it doesn't work in material buttons... Mar 2, 2023 at 9:56
4

I can't add a comment yet, so I'm posting as an answer instead.

I just want to say that Bojan Kseneman's answer (https://stackoverflow.com/a/30717100/2771087) is fantastic. There's one issue with it that I'd like to correct, though.

Rather than finding the end position of the last character in a line, it's grabbing the end of second last character and then adding the width of the first character in the line. These two lines here:

x_diff = layout.getPrimaryHorizontal(firstCharInLine + 1) - x_start;
x_stop = layout.getPrimaryHorizontal(lastCharInLine - 1) + x_diff;

Instead of this, getSecondaryHorizontal() can be used to grab the opposite side of the character, as in:

x_stop = layout.getSecondaryHorizontal(lastCharInLine);

However, this will also underline the space at the end of each line for multi-line text areas. So to fix that issue, use code like the following to skip past it before calculating x_stop:

while (lastCharInLine != firstCharInLine &&
       Character.isWhitespace(getText().charAt(lastCharInLine - 1))) {
    lastCharInLine--;
}
1
  • Very nice! Not so "stubby" after all!
    – dell116
    Jun 24, 2019 at 14:24
4
imee.setText(Html.fromHtml("<font color=#9e4c4e>  <u>" + ime + "</u>  </font>"));
avtorr.setText(Html.fromHtml("<font color=#90494f>  <u>" + avtorr + "</u>  </font>"));

The best solution is with using Html.

4

Another solution, also with span

ColoredUnderlineSpan.kt

/**
 * A span which draw a colored line below the text
 *
 * @property color The color of the underline
 * @property thickness The thickness of the line in pixels
 */
@RequiresApi(Build.VERSION_CODES.Q)
class ColoredUnderlineSpan(@ColorInt private val color: Int, @Px private val thickness: Float) : CharacterStyle(), UpdateAppearance {
    override fun updateDrawState(tp: TextPaint) {
        tp.underlineColor = color
        tp.underlineThickness = thickness
    }
}

/**
 * A span which draw a colored line below the text
 *
 * @param color The color of the underline
 * @property thickness The thickness of the line in pixels
 */
class ColoredUnderlineSpanPreQ(@ColorInt color: Int, @Px private val thickness: Float) : ReplacementSpan() {

    private val linePaint = Paint().apply {
        this.color = color
    }

    override fun draw(canvas: Canvas, text: CharSequence, start: Int, end: Int, x: Float, top: Int, y: Int, bottom: Int, paint: Paint) {
        canvas.drawText(text, start, end, x, y.toFloat(), paint)
        canvas.drawRect(x, bottom - thickness, (x + paint.measureText(text, start, end)), bottom.toFloat(), linePaint)
    }

    override fun getSize(
        paint: Paint,
        text: CharSequence,
        start: Int,
        end: Int,
        fm: Paint.FontMetricsInt?
    ): Int = paint.measureText(text, start, end).roundToInt()
}
0

This works great for me:

terms.setText(Html.fromHtml("I have read and agree to the <u><font color='red'>Terms and Conditions</u>"));
0

If it one line (short) text it is possible to solve it very easy way in XML file This example is grey text with orange underline on white background

{
    <LinearLayout
        android:id="@+id/textUnderLineLayout"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:background="@color/color_orange">

        <TextView
                android:id="@+id/underlined_text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="0dp"
                android:layout_marginStart="0dp"
                android:layout_marginEnd="0dp"
                android:layout_marginBottom="1dp"
                android:text="@string/some_text_string"
                android:textColor="@color/color_grey"
                android:background="@color/color_white"/>
    </LinearLayout>

}
0

Inspired by this android developer's answer, I come up with another solution, for better understanding the bounds and position of the underline.

text_underline.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:height="1dp"
        android:gravity="bottom|center_horizontal"
        android:left="1dp"
        android:right="1dp">

        <shape android:shape="rectangle">
            <!--<corners android:radius="2dp" /> -->
            <solid android:color="#D9FFFFFF" />
            <!--background color of box-->
        </shape>
    </item>
</layer-list>

usage in TextView or Button:

SpannableString(text).apply {
    setSpan(object : ReplacementSpan() {
        @SuppressLint("UseCompatLoadingForDrawables")
        private val drawable: Drawable = resources.getDrawable(R.drawable.text_underline, null)

        override fun draw(canvas: Canvas, text: CharSequence, start: Int, end: Int, x: Float, top: Int, y: Int, bottom: Int, paint: Paint) {
            drawable.setBounds(x.toInt(),
                top,
                (x + measureText(paint, text, start, end)).toInt(),
                (bottom + (buttonHeight - (bottom - top)) / 2.0f).roundToInt())

            canvas.drawText(text, start, end, x, y.toFloat(), paint)
            drawable.draw(canvas)
        }

        override fun getSize(paint: Paint, text: CharSequence, start: Int, end: Int, fm: Paint.FontMetricsInt?): Int =
            paint.measureText(text, start, end).roundToInt()

        private fun measureText(paint: Paint, text: CharSequence, start: Int, end: Int): Float = paint.measureText(text, start, end)

    },
        0,
        text.length,
        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

    setText(this, BufferType.SPANNABLE)
}

buttonHeight is the height of the View you want to apply the underline style to.

Here is the result: enter image description here

-1
    Paint p = new Paint();
    p.setColor(Color.RED);

    TextView t = (TextView) findViewById(R.id.textview);
    t.setPaintFlags(p.getColor());
    t.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
    t.setText("Underline Text");    

make a new paint color. and assign the paint to the textview.

5
  • Color.RED is for choosing the paint's color.
    – Ahmed Ekri
    Sep 27, 2013 at 9:00
  • and tell me what u get/see
    – Ahmed Ekri
    Sep 27, 2013 at 9:57
  • Still not working, "UNDERLINE_TEXT_FLAG" is a static field, so it doesn't matter what 'p' is.
    – Vipul J
    Sep 27, 2013 at 10:10
  • it's a warning. When u run ur app, what do u see/ happens ?
    – Ahmed Ekri
    Sep 27, 2013 at 11:05
  • Nothing, underlines with same color as before. And that warning means it won't work.
    – Vipul J
    Sep 27, 2013 at 14:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.