I've implemented a solution which, in my opinion, is more elegant. I've made a custom TextView
. This way you don't need to execute extra code for every TextView
with hyperlinks.
package com.example.view;
import android.content.Context;
import android.support.v7.widget.AppCompatTextView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.URLSpan;
import android.util.AttributeSet;
import com.example.utils.UrlSpanNoUnderline;
public class TextViewNoUnderline extends AppCompatTextView {
public TextViewNoUnderline(Context context) {
this(context, null);
}
public TextViewNoUnderline(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.textViewStyle);
}
public TextViewNoUnderline(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setSpannableFactory(Factory.getInstance());
}
private static class Factory extends Spannable.Factory {
private final static Factory sInstance = new Factory();
public static Factory getInstance() {
return sInstance;
}
@Override
public Spannable newSpannable(CharSequence source) {
return new SpannableNoUnderline(source);
}
}
private static class SpannableNoUnderline extends SpannableString {
public SpannableNoUnderline(CharSequence source) {
super(source);
}
@Override
public void setSpan(Object what, int start, int end, int flags) {
if (what instanceof URLSpan) {
what = new UrlSpanNoUnderline((URLSpan) what);
}
super.setSpan(what, start, end, flags);
}
}
}
And code for UrlSpanNoUnderline:
package com.jankstudios.smmagazine.utils;
import android.text.TextPaint;
import android.text.style.URLSpan;
public class UrlSpanNoUnderline extends URLSpan {
public UrlSpanNoUnderline(URLSpan src) {
super(src.getURL());
}
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
}
}
tel:2125551212
. Thenew URLSpanNoUnderline
call should be passedspan.getURL()
to retain this info, otherwise you generate bad links that cause exceptions when clicked. I've placed this proposed solution in the edit queue for your answer, since I don't have edit permissions myself. – Gaddy