Android Textview 改变行间距/填充

use*_*442 1 android textview

我正在尝试在bottomsheetdialog 中创建一个文本视图,示例布局如下所示。我已将所需的格式注释放在括号中 大多数跨文本(粗体、下划线等)都很容易创建

使用“\n\n”可以轻松设置 2 的行距,但如何在某些行之间创建 1.5 的行距?我使用append(...)动态添加文本,所以我不能在布局xml中使用android:text属性。我见过的大多数示例都将行距硬连接到 xml 中,这适用于所有文本。我发现您可以为段落应用不同的行距,但“\n”会破坏段落,并且不同的行距不起作用。

title (underlined, bold, very large)
(linespace 1.5)
blurb
(linespace 2)
sub-section1 (underlined, bold, large)
(linespace 1.5)
ClickableSubheading1 
(linespace 1.5)
clickableSubheading2
(linespace 1.5)
[could be many more subheadings here...]

(linespace 2)
sub-section2 (underlined, bold, large)
(linespace 1.5)
ClickableSubheading1a 
(linespace 1.5)
clickableSubheading2a
(linespace 1.5)
[could be many more subheadings here...]


etc - more subsections to be added as and when needed
Run Code Online (Sandbox Code Playgroud)

注意:可点击的子标题将隐式代码应用于应用程序,而不是超链接(我考虑将所有内容作为 html 进行,然后将其读入我的文本视图)基本上,我需要的是一个跨度,或类似的内容,即“把换行符,m 次 '\n' ”,其中 'm' 可以是任何值

Pha*_*inh 7

您可以使用RelativeSizeSpan将第二个的大小缩放'\n'为较小的值。

喜欢

// I try to find all '\n\n' in TextView then I resize the second \n size to 0.5
private fun beautifulParagraph(textView: TextView) {
    val text = textView.text
    var startIndex = 0
    val sb = SpannableString(text)
    var index: Int
    while (text.indexOf("\n\n", startIndex).also { index = it } != -1) {
        sb.setSpan(RelativeSizeSpan(0.5f), index + 1, index + 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        startIndex = index + 2
    }
    textView.text = sb
}
Run Code Online (Sandbox Code Playgroud)

使用

beautifulParagraph(yourTextView)
Run Code Online (Sandbox Code Playgroud)

XML

<TextView
        android:id="@+id/tv_heelo"
        android:layout_width="150dp"
        android:layout_height="match_parent"
        android:text="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n\nbbbbbbbbbbbbbbbnbbbbbbbbbbbbbbbnbbbbbbbbbbbbbbbnbbbbbbbbbbbbbbb\n\nccccccccccccccccnccccccccccccccccnccccccccccccccccnccccccccccccccccncccccccccccccccc\n\nddd"
        android:textSize="15sp"
        android:layout_margin="20dp"
        android:background="#000"
        android:textColor="#fff"
/>
Run Code Online (Sandbox Code Playgroud)

结果(未调整大小和调整大小)

------>