1
我有一個文本和一個包含7個單詞的數組(textviewArray)。在我的文本中存在這7個詞。我想用粗體在這段文字中顯示這7個單詞。用SetSpan和循環以粗體顯示文本中的單詞
我有這樣的代碼,但最後一個字是勇敢的,不是所有的七個字:
我有一個文本和一個包含7個單詞的數組(textviewArray)。在我的文本中存在這7個詞。我想用粗體在這段文字中顯示這7個單詞。用SetSpan和循環以粗體顯示文本中的單詞
我有這樣的代碼,但最後一個字是勇敢的,不是所有的七個字:
嘗試
String text = "text here";
String[] wordsToBold = {"word1", "word2", "word3", "word4", "word5", "word6", "word7"}
SpannableString spanString = FontUtility.getMultiFontText(context, "fonts/myfont.ttf", text, wordsToBold);
public static SpannableString getMultiFontText(Context context, int fontPathFromAssets, String text, String[] wordsToBold){
SpannableString spannableString = new SpannableString(text);
for(String word : wordsToBold) {
int startIndex = text.indexOf(word);
while(startIndex >= 0) {
int endIndex = startIndex+word.length();
spannableString.setSpan(new CustomTypefaceSpan(context, context.getString(fontPathFromAssets)), startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
startIndex = text.indexOf(word, endIndex + 1);
}
}
return spannableString;
}
爲什麼不設置文本樣式大膽,如果你想顯示的所有文字BOLD –
你需要在循環內創建'bss' – pskink
@pskink我把bss放入循環中,現在我看到所有7個單詞都是粗體的。謝謝。我們爲什麼要這樣做? – arz