Skip to main content

How to change the background color of a button in Kotlin Android

How to change the background color of a button in Kotlin Android.

Here's a step-by-step tutorial on how to change the background color of a button in Kotlin Android:

Step 1: Create a new Android project

Start by creating a new Android project in Android Studio. Choose an appropriate project name, package name, and select the minimum SDK version you want to support.

Step 2: Create a button in the layout file

Open the layout file (usually named activity_main.xml) and add a button element. You can do this by dragging and dropping a Button widget from the Palette onto the layout editor, or by manually adding the code. Make sure to give the button an id attribute so that you can reference it in your Kotlin code.

<Button
android:id="@+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me" />

Step 3: Reference the button in your Kotlin code

Open the MainActivity.kt file and import the necessary packages. Then, create a reference to the button by calling the findViewById() method and passing the button's id as an argument.

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button

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

val myButton: Button = findViewById(R.id.myButton)
}
}

Step 4: Change the background color programmatically To change the background color of the button, you can use the setBackgroundColor() method. This method takes a color value as an argument. In Kotlin, you can define a color using the Color class from the android.graphics package.

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.graphics.Color

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

val myButton: Button = findViewById(R.id.myButton)
myButton.setBackgroundColor(Color.RED)
}
}

In the above example, we set the background color of the button to red using the Color.RED constant. You can replace it with any other color of your choice by using the appropriate constant or by specifying a custom color value.

Step 5: Run the app

Finally, run the app on an emulator or a physical device to see the button with the changed background color. You should now see the button with the specified background color when the app is launched.

That's it! You have successfully changed the background color of a button in Kotlin Android. You can experiment with different colors and customize the button's appearance as per your requirements.