2017-10-09 205 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