Android 不一致的SpannableString setSpan()着色?
我试图在我的字符串中只给元音加上颜色1(例如红色),而给非元音加上颜色1(例如蓝色)。但是当遍历每个字符时,SpannableString setSpan()方法是不一致的。该函数正确检测誓言和非誓言,因为我已经检查了记录的输出,但颜色不正确:Android 不一致的SpannableString setSpan()着色?,android,spannable,Android,Spannable,我试图在我的字符串中只给元音加上颜色1(例如红色),而给非元音加上颜色1(例如蓝色)。但是当遍历每个字符时,SpannableString setSpan()方法是不一致的。该函数正确检测誓言和非誓言,因为我已经检查了记录的输出,但颜色不正确: //ColorLogic.java: public SpannableString colorString(String myStr) { SpannableString spnStr=new SpannableString(my
//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]
//ColorLogic.java:
公共SpannableString colorString(字符串myStr)
{
SpannableString spnStr=新SpannableString(myStr);
ForegroundColorSpan=新的ForegroundColorSpan(Color.RED);
ForegroundColorSpan conColor=新的ForegroundColorSpan(Color.BLUE);
int strLen=myStr.length();
对于(int i=0;i
不能重复使用跨对象。正如pskink所指出的,请为每个
setSpan()
调用使用不同的ForegroundColorSpan
对象
此外,您可能希望总体上使用较少的跨距。虽然您的示例(“Abibubu”)要求尽可能多的跨距,但大多数单词的辅音和元音串在一起。例如,“辅音”一词有两个辅音跨度(“ns”和“nt”)。可以使用一个而不是两个ForegroundColorSpan
对它们进行着色,从而提高渲染速度。跨度很容易,但不是最快的,因此使用的跨度越小,应用程序的性能越好,特别是在动画环境中(例如,在列表视图中滚动)
此外,您可能只需要为辅音或元音添加颜色,除非您计划为连字符和撇号添加第三种颜色。请记住:您的文本可以以颜色开头(例如,android:textColor
)。为每个vovel/非vovelI创建一个新的跨度。我已经尝试为for循环的每个迭代在.setSpan中为元音或辅音声明一个新的跨度。这同样是不可预测和不正确的output@jerryh91:那么我们无法帮助您,因为您在问题中使用的代码不是您正在运行的代码。话虽如此,我建议您多考虑一下setSpan()
的第四个参数。