-1

I get the Text from the internet and put the data in a "FeedItem"-class. Now, I want to check the text whether it contains a "@". So, here is my code so far:

        // Check for empty status message
        if (!TextUtils.isEmpty(item.getStatus())) {
            if (item.getStatus().contains("@")) {
                String[] splited = item.getStatus().toString().split("\\s+");
                Spannable word = new SpannableString(item.getStatus());
                for (int i = 0; i < splited.length; i++) {
                    if (splited[i].toString().contains("@")) {

                        SpannableString s = SpannableString.valueOf(splited[i].toString());
                        s.setSpan(new ForegroundColorSpan(Color.BLUE), 0, word.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    }
                }
                statusMsg.setText(word);

            } else {
                statusMsg.setTextColor(R.color.black);
                statusMsg.setText(item.getStatus());
            }
            statusMsg.setVisibility(View.VISIBLE);

I worked with SpannableString and Html.fromHtml but it didn't work for me. The for loop gives me each word from the String. Now if one word contains the "@" i want to colorize only this word. Thanks.

fabiruu111
  • 79
  • 2
  • 14
  • Try out this solution [link](http://stackoverflow.com/a/34961310/2183890) – Ahsan Kamal Jan 31 '16 at 10:37
  • @AKSiddique Thanks for your answer. But I don't know the length of the string because it is dynamically changing. – fabiruu111 Jan 31 '16 at 10:39
  • 1
    Store your string in temporary variable and get their length by String.length method and pass value in above link Spannable. – Ahsan Kamal Jan 31 '16 at 10:48
  • you can use this http://stackoverflow.com/questions/2615749/java-method-to-get-position-of-a-match-in-a-string and this http://stackoverflow.com/questions/4032676/how-can-i-change-color-part-of-a-textview – Ilan Kutsman Jan 31 '16 at 11:53

1 Answers1

1

It looks like you want to highlight user mentions. I recommend using a regular expression for that:

if (status.contains("@")) {
    SpannableString s = SpannableString.valueOf(status);
    final Matcher matcher = Pattern.compile("[@]+[a-zA-Z0-9_.]+\\b").matcher(status);
    while (matcher.find()) {
        s.setSpan(new ForegroundColorSpan(Color.BLUE), matcher.start(), matcher.end(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    statusMsg.setText(s);
}

Best would be to move the Pattern.compile() call to a private static constant.

Matthias Robbers
  • 15,689
  • 6
  • 63
  • 73