I am trying to span the same string wherever it's showing in the paragraph.But the problem is its spanning the only first string wherever it matches in the paragraph.
e.g Hello this is my String in the paragraph. String is mutable.
In this case i want to span the word "String" wherever it's using in the line or paragraph. In the current implementation its spanning only first time wherever it matches with the paragraph and not checking rest of the paragraph. Please help me on this.
public void setClickableText(final Context context, String[] hyperText) {
String text = getText().toString();
SpannableStringBuilder stringBuilder = new SpannableStringBuilder(text);
for (int i=0; i<hyperText.length; i++) {
if (text.indexOf(hyperText[i]) > 0) {
subString = hyperText[i];
}
int startIndex = text.indexOf(subString);
int endIndex = startIndex + subString.length();
stringBuilder.setSpan(createSpan(subString), startIndex,endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
this.setText(stringBuilder);
this.setMovementMethod(LinkMovementMethod.getInstance());
}
private ClickableSpan createSpan(final String forString) {
return new ClickableSpan() {
@Override
public void onClick(View textView) {
if (listener != null) {
listener.onClickHyperText(forString);
}
}
@Override
public void updateDrawState(TextPaint state) {
super.updateDrawState(state);
state.setUnderlineText(false);
state.setColor(ContextCompat.getColor(getContext(), R.color.citiLinkColor));
}
};
}
Method calling
text.setClickableText(context, new String[]{"String"});
You need an inner loop that uses indexOf(String, int)
to step through the positions where each hyperText[i]
occurs. Something like this:
for (int i = 0; i < hyperText.length; i++) {
int pos = 0;
while ((pos = text.indexOf(hyperText[i], pos)) > 0) {
int end = pos + hyperText[i].length();
stringBuilder.setSpan(createSpan(hypertext[i]), pos, end,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
pos = end;
}
}
Note that this methodology for finding matches for the words is ignoring word boundaries and overlapping words / spans. You may want to rethink ...