不一致的SpannableString setSpan()着色?

时间:2013-12-08 16:42:39

标签: android spannable

我正在尝试仅为我的String 1颜色(前红色)中的元音着色,而非另一个非元音(例如:蓝色)。但是,当通过每个char迭代时,SpannableString setSpan()方法是不一致的。该函数正确检测誓言和非誓言,因为我检查了记录的输出,但着色不正确:

//ColorLogic.java:
public SpannableString colorString(String myStr)
    {
        SpannableString spnStr=new SpannableString(myStr);
        ForegroundColorSpan vowColor=new ForegroundColorSpan(Color.RED);
        ForegroundColorSpan conColor=new ForegroundColorSpan(Color.BLUE);
        int strLen=myStr.length();
        for(int i=0; i< strLen; i++)
        {
            if (vowSet.contains(Character.toLowerCase(myStr.charAt(i))))
            //if (i%2==0)
            {
                 Log.v(DTAG, "vow"+myStr.charAt(i));
                 spnStr.setSpan(vowColor, i, i, 0);

            }
            else
            {
                Log.v(DTAG, "cons"+myStr.charAt(i));
                spnStr.setSpan(conColor, i, i, 0);
            }
        }
        return spnStr;
    }

    //In my OnCreate of my activity class:
    //PASS
     //Log.v(DTAG, message);
     // Create the text view
     TextView textView = new TextView(this);
     textView.setTextSize(50);

     //Call Color Logic to color each letter individually
     ColorLogic myColorTxt=new ColorLogic();
     SpannableString spnMsg=myColorTxt.colorString(message);
     //Log.v(DTAG, "spnMsg: "+spnMsg.toString());

     textView.setText(spnMsg, BufferType.SPANNABLE);
    //textView.setTextColor(Color.GREEN);
     setContentView(textView);
     }


      ![Vows Only its correct (non-vowels only is correct as well)][1]
          ![With cons and vows, 2 letters then its incorrect!][2]

Alternating vows and cons is incorrect as well

1 个答案:

答案 0 :(得分:1)

您无法重复使用span对象。正如pskink所示,请为每个ForegroundColorSpan电话使用不同的setSpan()个对象。

此外,您可能希望整体使用更少的跨度。虽然你的样本(“abibobu”)需要尽可能多的跨度,但大多数单词都有辅音和元音串在一起。例如,“辅音”一词有两个双辅音跨度(“ns”和“nt”)。这些可以使用单个ForegroundColorSpan而不是两个来着色,从而提高渲染速度。跨度很简单,但速度不是最快,因此使用的跨度越少,应用程序的性能就越好,特别是在动画情境中(例如,在ListView中滚动)。

此外,您可能只需要为 辅音元音着色,除非您计划使用连字符和撇号的第三种颜色。请记住:您的文字可以以颜色开头(例如android:textColor)。

相关问题