How to format text (eg., adding bullet points, line breaks) in a TextView in Kotlin Android
How to format text (eg., adding bullet points, line breaks) in a TextView in Kotlin Android.
Here's a step-by-step tutorial on how to format text in a TextView in Kotlin Android.
Step 1: Create a new project
Start by creating a new project in Android Studio. Choose an appropriate name and package for your project.
Step 2: Design the user interface
Open the layout file (activity_main.xml) and add a TextView element. You can do this by dragging and dropping a TextView from the Palette onto the design view or by manually adding the XML code.
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textColor="@android:color/black"
android:padding="8dp" />
Step 3: Access the TextView in Kotlin code
In your Kotlin code (MainActivity.kt), you need to access the TextView to apply formatting. Add the following code inside the onCreate() method:
val textView = findViewById<TextView>(R.id.textView)
Step 4: Add bullet points
To add bullet points to your text, you can use the "•" symbol. Here's an example:
val bulletPoint = "\u2022"
val textWithBullets = "$bulletPoint First point\n$bulletPoint Second point\n$bulletPoint Third point"
textView.text = textWithBullets
Step 5: Add line breaks
To add line breaks in your text, you can use the "\n" escape sequence. Here's an example:
val textWithLineBreaks = "First line\nSecond line\nThird line"
textView.text = textWithLineBreaks
Step 6: Apply other formatting options
You can apply various formatting options to a TextView using its properties. For example, you can change the text color, text size, or padding. Here's an example:
textView.setTextColor(Color.RED)
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18f)
textView.setPadding(16, 16, 16, 16)
Step 7: Run the app
Now you can run the app on an emulator or a physical device to see the formatted text in the TextView.
Congratulations! You have successfully formatted text in a TextView in Kotlin Android.