2016-05-31 26 views
0

例如,我有一個textview(多行):aaaaaaaaabbbbaaa。我只想爲「bbb」字符設置背景。我嘗試使用Spannable,但它不起作用,我的背景是可繪製的圖像。 非常感謝。僅爲TextView的一部分設置背景

+0

請張貼代碼和佈局截圖以查看它的外觀。 – blizzard

+0

嘗試'ReplacementSpan'而不是 – pskink

+0

我不相信有一個內置的跨度可以處理您的用例。您可以嘗試創建自定義跨度。或者,使用多個「TextViews」。或者,使用「WebView」。 – CommonsWare

回答

1

enter image description here

使用BackgroundColorSpan你能做到這一點,但在正確的方式中國不`噸的工作。

private void replaceText(TextView text, String str, int color) { 
    Spannable raw = new SpannableString(text.getText()); 
    BackgroundColorSpan[] spans = raw.getSpans(0,raw.length(),BackgroundColorSpan.class); 

    for (BackgroundColorSpan span : spans) { 
     raw.removeSpan(span); 
    } 
    int index = TextUtils.indexOf(raw, str); 
    while (index >= 0) { 
     raw.setSpan(new BackgroundColorSpan(color), index, index + str.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 
     index = TextUtils.indexOf(raw, str, index + str.length()); 
    } 
    text.setText(raw); 
} 
+0

謝謝先生,但如果我需要添加背景是一個圖像(不soild顏色),有可能的? –

+0

謝謝。它工作得很好 –