So I am trying to highlight the text view based on words but my code is not working properly what i want to do is "Hello world" both the word comes in different colour but for me only the hello part is getting highlighted
SpannableString spannableString = new SpannableString(all_folder.get(position).getAudioChineseText());
String spannableword = all_folder.get(position).getAudioChineseText();
String[] splitStr = spannableword.split("\\s+");
int end = 0;
for (int i = 0; i < splitStr.length; i++) {
end = splitStr[i].length() + i;
int start=splitStr[i].length()+1;
textcolor(holder.textChines, spannableString, i, end, all_folder.get(position).getSpeechResponse());
}
the textcolour method is working fine but the position is not getting passed properly any idea what i am doing wrong as i need to pass the start and end position of the word
You can make use of String#lastIndexOf
and String#indexOf
to get the spanned index. Below is an example .
private SpannableString getSpanString(String text){
SpannableString spannableString = new SpannableString(text);
int startIndex1= 0;
int endIndex1= text.indexOf(" ");
int startIndex2= text.lastIndexOf(" ");
int endIndex2 = text.length();
spannableString.setSpan(new ForegroundColorSpan(Color.RED), startIndex1, endIndex1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableString.setSpan(new ForegroundColorSpan(Color.BLUE), startIndex2, endIndex2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannableString;
}
Of course you need handle the edge cases here first . Like if String only have one word or its blank but the idea remain the same. Give it a try after adding the edge cases in the beginning of the method . Also you have to trim the string before use.