Skip to main content

How to set the background color of a TextView in Kotlin Android

How to set the background color of a TextView in Kotlin Android.

Here is a step-by-step tutorial on how to set the background color of a TextView in Kotlin for Android:

  1. Create a new Android project in your preferred IDE (e.g., Android Studio) and open the layout file where you want to add the TextView.

  2. In the layout file, add a TextView element by using the following code:

<TextView
android:id="@+id/myTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!" />
  1. Open the corresponding Kotlin file (e.g., MainActivity.kt) and import the necessary classes:
import android.graphics.Color
import android.os.Bundle
import android.widget.TextView
  1. Inside the onCreate method, initialize the TextView by finding its view using the findViewById method:
val myTextView = findViewById<TextView>(R.id.myTextView)
  1. To set the background color of the TextView, you can use the setBackgroundColor method and pass a color value to it. For example, to set the background color to red, use the following code:
myTextView.setBackgroundColor(Color.RED)
  1. You can also set the background color using a hexadecimal color code. For example, to set the background color to a light blue (#87CEFA), use the following code:
myTextView.setBackgroundColor(Color.parseColor("#87CEFA"))
  1. If you want to set a transparent background color, you can use the Color.argb method. For example, to set the background color to semi-transparent green with an alpha value of 50%, use the following code:
myTextView.setBackgroundColor(Color.argb(128, 0, 255, 0))
  1. After setting the background color, run your Android application and you will see the TextView with the specified background color.

That's it! You have successfully set the background color of a TextView in Kotlin for Android. You can experiment with different color values and customize the appearance of your TextView as desired.