【问题标题】:Inconsistent SpannableString setSpan() coloring?SpannableString setSpan() 着色不一致?
【发布时间】:2013-12-08 16:42:38
【问题描述】:

我试图只用我的字符串 1 颜色(例如红色)为元音着色,而另一种颜色(例如:蓝色)为非元音。但是 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]

【问题讨论】:

  • 为每个元音/非元音创建一个新的跨度

标签: android spannable


【解决方案1】:

您不能重复使用 span 对象。正如 pskink 所指出的,请为每个 setSpan() 调用使用不同的 ForegroundColorSpan 对象。

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

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

【讨论】:

  • 我已经尝试为 for 循环的每次迭代在 .setSpan 中为元音或辅音声明一个新的跨度。同样是不可预测且不正确的输出
  • @jerryh91:那么我们无法帮助您,因为您在问题中的代码不是您正在运行的代码。话虽如此,我建议您多考虑setSpan() 的第四个参数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多