Search code examples
javaandroidkotlintextviewstringbuilder

String Builder not working in TextView Android Kotlin


Hey I want to give space\tab between two words in a string to display in TextView. I have mutableListOf of string and doing iteration for each string. In Iteration i searching first space and replacing with \t and storing in string builder it working fine what i want and checking in logs it's fine. But i set texting it not working in text view.

    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

As you see it fine in logs

In Logs

But when i am setting text in text view it's not working

Not Working

Also i want to give margin/padding between lines i.e. 1st point has some margin bottom/padding bottom to 2nd point i don't use \n


Solution

  • You do not need to use StringBuilder to complete your requirements. I use joinToString to solve this problem.

        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 = "")
        }
    

    As for how to modify the spacing between the first line and the second line, you can set android:lineHeight="40dp" to solve

        <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