how to change the color of text partially in android

Viewed 932

I have a sentence that contains message to be posted to the server like wow! superb pic #superb #pic #111 #222 enjoyed the pic

I want to extract the hastags and make them colored and leaving the rest of the text intact.

I tried the following code but not working.

private void spannableOperationOnHastag() {
        mPostMessage = edPostMessage.getText().toString().trim();
        String strPreHash = null;
        String strHashText = "";
        if (mPostMessage.contains("#")) {
            try {
                int index = mPostMessage.indexOf("#");
                strPreHash = mPostMessage.substring(0, index);
                SpannableString spannableString = new SpannableString(strPreHash);


                String strHashDummy=mPostMessage.substring(index, mPostMessage.length());
                int hashCount= StringUtils.countMatches(strHashDummy, "#"); // check for number of "#" occurrence and run forloop for getting the number of hastags in the string
                int hasIndex=0;
                for (int i = 0; i <hashCount ; i++) {
                    strHashText = strHashText+strHashDummy.substring(hasIndex, strHashDummy.indexOf(' '))+" ";
                    hasIndex =strHashText.indexOf(" "); // updating new space(" ") position in the index variable
                }


                SpannableString spannableStringBlue = new SpannableString(strHashText);
                spannableStringBlue.setSpan(new ForegroundColorSpan(PublishPostActivity.this.getResources().getColor(R.color.blue)), 0, strHashText.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                edPostMessage.setText(null); // clearing old string
                edPostMessage.append(spannableString); // setting extracted coloured text
                edPostMessage.append(spannableStringBlue);
            } catch (Exception e) {
                Log.d(TAG, "validatePostMessage() called with " + "e = [" + e + "]");
            }
        }
    }
4 Answers
Related