Hello All
在我的android项目中,我想显示一个特定的单词,在字符串中说TRIAL这是我的Trial.This试验只是为了好玩。 如何在android中实现这一点。
我尝试使用下面的代码,它只会格式化15到30之间的字符串。
TextView TV = (TextView)findViewById(R.id.mytextview01);
Spannable WordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");
WordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
TV.setText(WordtoSpan);
请告诉我是否可以在Android中执行此操作。
请转发您宝贵的建议。
提前致谢:)
答案 0 :(得分:0)
尝试在String类中使用indexOf(String str)方法。这将为您提供您在Spannable中搜索的单词的第一次出现(这是一个扩展的字符串)。然后,您可以相应地应用颜色范围。
答案 1 :(得分:0)
在Scythe的答案上稍微扩展一下,用以下内容替换它们:
public class Junk extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.textView1);
String tvText = "This is for my Trial.This Trial is just for fun. Just a Trial";
tvText+="A Trial. Only a Trial. It's a Trial";
String lookFor = "Trial";
tv.setText(formatString(tvText, lookFor));
}
private Spannable formatString(String targetStr, String lookFor) {
Spannable spanString = null;
spanString = new SpannableString(targetStr);
int fromIndex, startSpan, endSpan;
fromIndex = 0;
while (fromIndex < (targetStr.length() - 1)) {
startSpan = targetStr.indexOf(lookFor, fromIndex);
if (startSpan == -1)
break;
endSpan = startSpan + lookFor.length();
spanString.setSpan(new ForegroundColorSpan(Color.BLUE), startSpan,
endSpan, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
fromIndex = endSpan;
}
return spanString;
}
}