2017-10-09 65 views
0

其實我試圖增加Spannable字符串中文本之間的行距。然後我想通過增加換行符的跨度大小來實現。但似乎第二條新線不受影響。Android:更改Spannable字符串中換行符的高度不起作用

起初我使用'a'作爲分隔符來表明代碼有效。

private fun getCenterSpannableText() : SpannableString { 
    val currency = "Currency" 
    val total = "Total" 
    val subtitle = "Subtitle" 
    val delimiter = "\n" 
    val finalStr = "$currency$delimiter$total$delimiter$subtitle" 

    val currencyIndex = finalStr.indexOf(currency) 
    val totalIndex = finalStr.indexOf(total) 
    val subtitleIndex = finalStr.indexOf(subtitle) 

    val s = SpannableString(finalStr) 
    s.setSpan(RelativeSizeSpan(1.4f), currencyIndex, currency.length, 0) 
    s.setSpan(ForegroundColorSpan(ContextUtil.instance.getColor(R.color.colorGrey5)), currencyIndex, currency.length, 0) 

    s.setSpan(RelativeSizeSpan(1.8f), totalIndex, totalIndex + total.length, 0) 
    s.setSpan(ForegroundColorSpan(ContextUtil.instance.getColor(R.color.colorGrey5)), totalIndex, totalIndex + total.length, 0) 

    s.setSpan(RelativeSizeSpan(1f), subtitleIndex, subtitleIndex + subtitle.length, 0) 
    s.setSpan(ForegroundColorSpan(ContextUtil.instance.getColor(R.color.colorGrey2)), subtitleIndex, subtitleIndex + subtitle.length, 0) 

    //make the \n have bigger fonts 
    s.setSpan(RelativeSizeSpan(2.5f), currencyIndex + currency.length, currencyIndex + currency.length + delimiter.length, 0) 
    s.setSpan(RelativeSizeSpan(2.5f), totalIndex + total.length , totalIndex + total.length + delimiter.length, 0) 

    return s 
} 

輸出是這樣的:

enter image description here

然後我改變分隔符爲 「\ n」,它看起來不正確:

enter image description here

林上運行它API24模擬器

回答

0

我覺得'發生的事是這樣的:

Currency\n 
Total\n 
Subtitle 

在這種情況下,你真的想這樣:

Currency\n 
Total\n 
Subtitle\n 

編輯: 這意味着你可能想嘗試更改您的代碼

val finalStr = "$currency$delimiter$total$delimiter$subtitle$delimiter" 
+0

爲什麼你會認爲我想這樣做?我希望所有3個值分別在不同的行上 – iori24

+0

您希望Total和Subtitle之間有更大的行距,不是嗎?你是否嘗試了我所建議的並且失敗,或者正在複製粘貼一行代碼,而不是試圖再次解釋它? 編輯:我不好,要編輯答案。它現在應該分開。 – Bjelis

+0

現在在最後添加換行符可以獲得更好的結果。然後,我需要爲最後一個新行添加另一個s.setSpan(RelativeSizeSpan()...),並圍繞這些值來獲得最佳結果。但我不明白爲什麼最後需要持續一個。謝謝btw – iori24