简体   繁体   中英

Android: Trying to change color from string

I'm trying to change the string color between these character * * , but something went wrong with my code. The application is finished. Every "nota" that contains "*" (ie This is * good * ) should change the color of the rest of word "good" and erase "*" characters

if(nota != null){
        if(nota.contains("* *")){

         nota = nota.replace("* *","");

         Spannable spannable = new SpannableString(nota);
         spannable.setSpan(new ForegroundColorSpan(Color.YELLOW), nota.indexOf("* *"), nota.indexOf("* *") + "* *".length(),     Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
         txtnota.setText(spannable);

    }
    }

UPDATE:

I tried this code, but it is partially coloring the words (not the specific word that I want):

if(nota != null){
        int firstIndex = nota.indexOf("*");
        if (firstIndex >= 0) {
            nota = nota.replaceFirst("[*]{1}", "");
            int secIndex = nota.indexOf("*");
            if (secIndex >= 0) {
                nota = nota.replaceFirst("[*]{1}", "");

                Spannable spannable = new SpannableString("➥ "+nota);
                spannable.setSpan(new ForegroundColorSpan(Color.YELLOW), firstIndex, secIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                spannable.setSpan(new android.text.style.StyleSpan(android.graphics.Typeface.BOLD_ITALIC), firstIndex, secIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                txtnota.setText(spannable);
            }
        }
}  

As I can see, you first remove the "*" character and after that you invoke indexOf that character, but you don't have it any more, so you get negative result. Move the replace instruction after setting span. And you shouldn't check for "* *" but for first occurence of "*" , than set span, and after that remove the two occurences of "*". Or you can keep indexes. Here is an example of code:

    if(nota != null){
            int firstIndex = nota.indexOf("*");
            if (firstIndex >= 0) {
                nota = nota.replaceFirst("[*]{1}", "");
                int secIndex = nota.indexOf("*");
                if (secIndex >= 0) {
                    nota = nota.replaceFirst("[*]{1}", "");

                    Spannable spannable = new SpannableString(nota);
                    spannable.setSpan(new ForegroundColorSpan(Color.YELLOW), firstIndex, secIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    txtnota.setText(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