Skip to main content

How to add ripple effect to a button in Kotlin Android

How to add ripple effect to a button in Kotlin Android.

Here's a detailed step-by-step tutorial on how to add a ripple effect to 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 and package name.

Step 2: Design the layout​

Open the layout file for the activity or fragment where you want to add the button with a ripple effect. In the XML layout file, add a Button element and provide it with an id attribute.

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

Step 3: Add the ripple drawable​

In order to add a ripple effect to the button, we need to create a ripple drawable. Create a new XML file in the drawable directory and name it "ripple_button.xml". Open the file and add the following code:

<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="?android:attr/colorControlHighlight">

<item android:id="@android:id/mask">
<shape android:shape="rectangle">
<solid android:color="#000000"/>
</shape>
</item>

<item>
<shape android:shape="rectangle">
<solid android:color="@color/colorPrimary"/>
</shape>
</item>

</ripple>

In the above code, we define a ripple drawable with two items. The first item defines a mask to overlay the ripple effect on top of the button. The second item defines the shape and color of the button.

Step 4: Apply the ripple drawable to the button​

Go back to the layout XML file and modify the Button element to apply the ripple drawable as the background of the button. Use the android:background attribute and set it to the drawable resource file.

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

Step 5: Handle button click events​

Now that the button has a ripple effect, let's handle its click events. In the activity or fragment code, find the button by its id and set an OnClickListener to handle the click events.

val myButton = findViewById<Button>(R.id.myButton)
myButton.setOnClickListener {
// Add your code here to handle button click events
}

Step 6: Build and run the app​

Finally, build and run the app on an Android device or emulator. You should now see the button with a ripple effect when clicked.

Congratulations! You have successfully added a ripple effect to a button in Kotlin Android. Experiment with different colors and shapes to customize the ripple effect according to your app's design.