I am working on an android app in which I have put a mail in a text in textView
and it is clickable. I want to remove the underline from the mail. How to do it?
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="@dimen/mailnlink"
android:textColor="@color/mltext"
android:textColorLink="@color/link"
android:textStyle="italic"
android:gravity="center"
android:autoLink="email"
android:background="@color/mlb"
android:text="@string/f2"/>
This worked for me: I added autolink in the xml or you can also use linkify in code.
<TextView
android:id="@+id/mail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="@dimen/mailnlink"
android:textColor="@color/mltext"
android:textColorLink="@color/link"
android:textStyle="italic"
android:gravity="center"
android:background="@color/mlb"
android:autoLink="email"
android:text="@string/f2"
/>
In the java file:
TextView mtextView = (TextView) findViewById(R.id.mail);
Spannable sa = (Spannable)mtextView.getText();
for (URLSpan u: sa.getSpans(0, sa.length(), URLSpan.class)) {
sa.setSpan(new UnderlineSpan() {
public void updateDrawState(TextPaint tp) {
tp.setUnderlineText(false);
}
}, sa.getSpanStart(u), sa.getSpanEnd(u), 0);
}ere
Here's a Kotlin extension function as a solution to remove all UrlSpan
underlines:
private fun Spannable.removeAllUrlSpanUnderline() {
for (urlSpan in getSpans(0, length, URLSpan::class.java)) {
setSpan(object : UnderlineSpan() {
override fun updateDrawState(tp: TextPaint) {
tp.isUnderlineText = false
}
}, getSpanStart(urlSpan), getSpanEnd(urlSpan), 0)
}
}
In my case, I began with a string with href tags. fromHtml
returns a Spanned
so cast it to a Spannable
so it's mutable. See the sample use below:
val sampleHtmlString = "<a href=\"www.google.com\">first Link</a> and <a href=\"www.google.com\">second link</a>"
val sampleSpannable = HtmlCompat.fromHtml(sampleHtmlString, HtmlCompat.FROM_HTML_MODE_LEGACY) as Spannable
sampleSpannable.removeAllUrlSpanUnderline()
Now you're free to set sampleSpannable
to your TextView
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With