Try the below code to remove underlined and clicked event on multiple words in textview :
String str="Angelina Clapped For Lester Kang";
Spannable span = Spannable.Factory.getInstance().newSpannable(str);
// 0 to 8 start and index of Angelina
span.setSpan(new ClickableSpan(str), 0, 8, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
// 21 to 32 start and index of Lester Kang
span.setSpan(new ClickableSpan(str), 21, 32, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textview.setText(span);
class ClickableSpan extends ClickableSpan{
String clicked;
public ClickableSpan (String string) {
super();
}
public void onClick(View v) {
Toast.makeText(MyActivity.this,""+((TextView)v).getText().toString(),Toast.LENGTH_SHORT).show();
}
public void updateDrawState(TextPaint ds) {
// override updateDrawState
ds.setUnderlineText(false); // set to false to remove underline
}
}
This works for me. No need to create custom ClickableSpan class. Just override updateDrawState(TextPaint ds).
SpannableString span = new SpannableString("Some text");
ClickableSpan clickSpan = new ClickableSpan() {
@Override
public void updateDrawState(TextPaint ds) {
ds.setColor(ds.linkColor); // you can use custom color
ds.setUnderlineText(false); // this remove the underline
}
@Override
public void onClick(View textView) {
// handle click event
}
};
span.setSpan(clickSpan, 5, span.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
yourTextView.setText(span);
string1 = new SpannableString("By Tapping Register You Agree To The \nTerms And Conditions");
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(View widget) {
Toast.makeText(getApplicationContext(),"clicked",Toast.LENGTH_SHORT).show();
}
@Override
public void updateDrawState(TextPaint ds) {
ds.setUnderlineText(false); // this line removes underline
}
};
text_terms.setMovementMethod(LinkMovementMethod.getInstance());
string1.setSpan(clickableSpan,37,string1.length(),0);
text_terms.setText(string1);
If you do not want any pre-applied attributes do not call super.updateDrawState(). On overriding updateDrawState(object:Textpaint) with help of object you can apply or call different functions present in Text Paint.
ANURAG RASTOGI's answer saved the day for me! I already have a formatted SpannableString on which I wanted to apply a ClickableSpan:
spannableString.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
// Do something...
}
// Prevent
// ds.setColor(ds.linkColor);
// ds.setUnderlineText(true);
// in: https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/text/style/ClickableSpan.java
// from executing.
@Override
public void updateDrawState(@NonNull TextPaint ds) {
// super.updateDrawState(ds);
}
},0, spannableString.length(), SPAN_EXCLUSIVE_EXCLUSIVE);
The updateDrawState overrides the updateDrawState in the ClickableSpan class in Android, and by not calling super.updateDrawState it will not get executed.
All text formatting already present in spannableString will be preserved.