简体   繁体   中英

how to change the color of text partially in android

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 + "]");
            }
        }
    }

I solved the problem my self . I any one needs it can refer this code :)

private void spannableOperationOnHastag() throws Exception{
        mPostMessage = edPostMessage.getText().toString()+" "; // extra space for spannable operations
        List<Integer> listStartPos = new ArrayList<>();
        List<Integer> listEndtPos = new ArrayList<>();

        if (mPostMessage.contains("#")){
            for (int i = 0; i < mPostMessage.length(); i++) {
                if (mPostMessage.charAt(i) == '#') {
                    listStartPos.add(i);
                    Log.d(TAG, "startIndex of # = " + i);
                }
            }
            for (int i = 0; i < listStartPos.size(); i++) {
                int endIndex = mPostMessage.indexOf(' ', listStartPos.get(i));
                listEndtPos.add(endIndex);
                Log.d(TAG, "endIndex of # " + (endIndex));
            }
            SpannableString spanned = SpannableString.valueOf(mPostMessage);
            for (int i = 0; i < listStartPos.size(); i++) {
                spanned = new SpannableString(spanned);
                spanned.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.blue)), listStartPos.get(i), listEndtPos.get(i), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                Log.d(TAG, "substring " + mPostMessage.substring(listStartPos.get(i), listEndtPos.get(i) + 1));
            }
            mPostMessage.trim(); // removing extra space.
            edPostMessage.setText(null);
            edPostMessage.setText(spanned);

        }
    }

I see you've just posted your own answer, but as I'd nearly finished typing this up I thought I'd go ahead and post this anyway :). I typed it just now without an IDE so it may not be perfect.

private static SpannableString convertTextColorsAtChar(char trigger, String inputText) {

    SpannableString spannedText = new SpannableString(inputText);

    if (!inputText.contains(trigger)) {
        return spannedText;
    }

    ArrayList<int[]> indexArr = getIndexes(trigger, inputText.toCharArray());

    for (int[] indexes : indexArr) {
        spannedText.setSpan(new ForegroundColorSpan(Color.RED), indexes[0], indexes[1], Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    returned spannedText;

}

private static ArrayList<int[]> getIndexes(char trigger, char[] inputText) {

    ArrayList<int[]> values = new ArrayList<int[]>();

    int firstIndex = -1;
    int secondIndex; = -1

    for (int i = 0; i < inputText.length; i++) {
        if (firstIndex != -1 && inputText[i] == ' ') {
            secondIndex = i;
            values.add(new int[] { firstIndex, secondIndex });
            firstIndex = secondIndex = -1;
        }
        if (trigger == inputText[i]) {
            firstIndex = i;
        }
    }

    return values;

}

You'd then call it with convertTextColorsAtChar('#', editText.getText().toString());

change your code as below

SpannableString spannableStringBlue = new SpannableString(strHashText);

 spannableStringBlue.setSpan(new ForegroundColorSpan(new ForegroundColorSpan(Color.BLUE), 0, strHashText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

edPostMessage.setText(null); // clearing old string
edPostMessage.append(spannableString); // setting extracted coloured text
edPostMessage.append(spannableStringBlue);
SpannableStringBuilder builder = new SpannableStringBuilder();
String yourSentence = "Pic #superb #pic #111 #222 enjoyed the pic";
String [] newSent = yourSentence.split(" ");

    for(int count = 0; count < newSent.length; count++){
       if(newSent[count].contains("#")){
          SpannableString redSpannable= new SpannableString(newSent[count]);
          redSpannable.setSpan(new ForegroundColorSpan(Color.RED), 0, newSent[count].length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

          Log.v("Test", "color_string" + newSent[count]);
          builder.append(redSpannable+" ");
        } else{
          builder.append(newSent[count]+" ");
          Log.v("Test", "normal_string" + newSent[count]);
          }
       }

    holder.PhName.setText(builder, TextView.BufferType.SPANNABLE);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM