将样式应用于Android字符串中的文本

时间:2014-03-24 15:05:58

标签: java android string styles contains

我正在尝试使用SpannableString创建一个String来应用颜色和粗体文本。

Spannable WordtoSpan = new SpannableString("Salida de la Capilla de María Auxiliadora\n00:00\nMarquesa de Sales\n00:00\nEspíritu Santo\n00:00\nSagasta\n00:00\nPza. Meneses\n00:00\nPozo Nuevo\n00:00\nPza. Ayuntamiento\n00:00\nSan Miguel\n00:00\nEstación de Penitencia, Iglesia San Miguel\n00:00\nÁnimas\n00:00\nMariano Hernández\n00:00\nEduardo Dato\n00:00\nRojas Marcos\n00:00\nPza. Meneses\n00:00\nCarrera\n00:00\nCalzadilla\n00:00\nGregorio María Ferro\n00:00\nMaría Auxiliadora\n00:00\nMarquesa de Sales\n00:00\nEntrada al Templo\n00:00\n");

tv.setText(WordtoSpan);

为了加快我的工作,我试图创建一个这样的条件:

if(WordtoSpan.toString().contains(":")){
// found the text string ":" (00:00)

WordtoSpan.setSpan(new ForegroundColorSpan(Color.rgb(140, 117, 189)), 42, 47, 
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
WordtoSpan.setSpan(new StyleSpan(Typeface.BOLD), 42,47, 47);
}else{
//Not found ":"
}

我会将粗体文本和颜色实现到所有字符串00:00。有谁知道任何快速简便的方法?不要用言语来说明填写所有00:00的文字吗?

问候!

1 个答案:

答案 0 :(得分:1)

找到索引“00:00”,并将其设置为span的起始索引,并将结束索引设置为“00:00”的长度

    Spannable WordtoSpan = new SpannableString("Salida de la Capilla de María Auxiliadora\n00:00\nMarquesa de Sales\n00:00\nEspíritu Santo\n00:00\nSagasta\n00:00\nPza. Meneses\n00:00\nPozo Nuevo\n00:00\nPza. Ayuntamiento\n00:00\nSan Miguel\n00:00\nEstación de Penitencia, Iglesia San Miguel\n00:00\nÁnimas\n00:00\nMariano Hernández\n00:00\nEduardo Dato\n00:00\nRojas Marcos\n00:00\nPza. Meneses\n00:00\nCarrera\n00:00\nCalzadilla\n00:00\nGregorio María Ferro\n00:00\nMaría Auxiliadora\n00:00\nMarquesa de Sales\n00:00\nEntrada al Templo\n00:00\n");

    String search = new String("00:00");
    int length = search.length();
    String input = WordtoSpan.toString();
    int startIndex = input.indexOf(search);
    while(startIndex > length)
    {
        WordtoSpan.setSpan(new ForegroundColorSpan(Color.rgb(140, 117, 189)), startIndex, startIndex + length,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        WordtoSpan.setSpan(new StyleSpan(Typeface.BOLD), startIndex, startIndex + length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        startIndex = input.indexOf(search, startIndex + length);
    }

您必须在索引

的整个字符串中循环