Skip to main content

How to change the text color of a TextView in Kotlin Android

How to change the text color of a TextView in Kotlin Android.

Here is a detailed step-by-step tutorial on how to change the text color of a TextView in Kotlin Android:

Step 1: Create a new Android project

To begin, open Android Studio and create a new Android project. Choose the project name, package name, and other required settings as per your preference.

Step 2: Add a TextView to the layout file

Open the XML layout file for the activity where you want to display the TextView. You can find the layout file under the "res" directory. Add the following code to create a TextView:

<TextView
android:id="@+id/myTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!"
/>

Step 3: Assign the TextView to a variable in the activity

In your activity class, declare a variable of type TextView and assign it the reference to the TextView in the layout file. Add the following code inside your activity class:

private lateinit var myTextView: TextView

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

myTextView = findViewById(R.id.myTextView)
}

Step 4: Change the text color programmatically

To change the text color of the TextView programmatically, you can use the setTextColor() method of the TextView class. This method accepts a color value as an argument. You can provide the color value as a resource reference or as a direct color value.

Example 1: Using a resource reference

myTextView.setTextColor(ContextCompat.getColor(this, R.color.red))

In this example, the text color of the TextView is set to the color defined in the red resource.

Example 2: Using a direct color value

myTextView.setTextColor(Color.RED)

In this example, the text color of the TextView is set to the predefined red color.

Step 5: Run the application

Finally, run the application on an emulator or a physical device to see the changes. The text color of the TextView should now be updated according to the code you have written.

That's it! You have successfully changed the text color of a TextView in Kotlin Android. You can experiment with different color values and apply the same technique to other TextViews in your project.