字符串生成器在 TextView Android Kotlin 中不起作用

问题描述

嘿,我想在字符串中的两个单词之间添加 space\tab 以在 TextView 中显示我有 mutablelistof 字符串并对每个字符串进行迭代。在迭代中,我首先搜索 space 并替换为 \t 并存储在 string builder 中,它可以正常工作,并且可以检查日志。但我设置发短信在文本视图中不起作用。

    val list = mutablelistof(
        "1. Log in Google account\n","2. Scroll to the page\n","3. Tap disconnect from account to logout"
    )
    val content = StringBuilder()
    list.forEach{ string->
        content.append(string.replaceFirst(" ","\t"))
    }
    System.out.print("string >> $content")
    list_string.text = content

正如你在日志中看到的那样

In Logs

但是当我在文本视图中设置文本时它不起作用

Not Working

我还想在行之间给 ma​​rgin/padding1st 点有一些边距底部/padding 底部2nd 点我不' t 使用 \n

解决方法

您不需要使用 StringBuilder 来完成您的要求。我使用joinToString来解决这个问题。

    private lateinit var tv: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main4)
        tv = findViewById(R.id.textView)
        val list = mutableListOf(
            "1. Log in Google account\n","2. Scroll to the page\n","3. Tap disconnect from account to logout"
        )
        list.forEach{ string->
            string.replaceFirst(" ","\t")
        }

        tv.text = list.joinToString(separator = "")
    }

至于如何修改第一行和第二行的间距,可以设置android:lineHeight="40dp"来解决

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toLeftOf="parent"
        android:lineHeight="40dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        />

image