Use below class i.e, yourTextView.setText(new RichTextView(sentence).setBold(wordWichYouwantBold))
You can find another useful method inside :) Enjoy!!!
import android.graphics.Typeface;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.StyleSpan;
import android.text.style.URLSpan;
import android.view.View;
/**
* Created by RajeshKushvaha on 19-11-16
*/
//.setText(text, TextView.BufferType.SPANNABLE); to textView if not work
public class RichTextView extends SpannableString {
private String syntax;
public RichTextView(String syntax) {
super(syntax);
this.syntax = syntax;
}
public RichTextView setTextColor(String word, int color) {
setSpan(new ForegroundColorSpan(color), syntax.indexOf(word), syntax.indexOf(word) + word.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return this;
}
public RichTextView setSize(String word, float howMuch) {
setSpan(new RelativeSizeSpan(howMuch), syntax.indexOf(word), syntax.indexOf(word) + word.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return this;
}
public RichTextView setStrikeOut(String word) {
setSpan(new StrikethroughSpan(), syntax.indexOf(word), syntax.indexOf(word) + word.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return this;
}
public RichTextView setUrl(String word, String redirectUrl) {
setSpan(new URLSpan(redirectUrl), syntax.indexOf(word), syntax.indexOf(word) + word.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return this;
}
public RichTextView setBold(String word) {
StyleSpan boldSpan = new StyleSpan(Typeface.BOLD);
setSpan(boldSpan, syntax.indexOf(word), syntax.indexOf(word) + word.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return this;
}
//setMovementMethod(LinkMovementMethod.getInstance()); after or before call
public RichTextView setClickable(String word, final setOnLinkClickListener listener) {
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(View view) {
if (listener != null) {
listener.onLinkClicked();
}
}
};
setSpan(clickableSpan, syntax.indexOf(word), syntax.indexOf(word) + word.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return this;
}
public interface setOnLinkClickListener {
public void onLinkClicked();
}
}