In this very short blog post I am going to share with you how to create and add Button in Kotlin programmatically. To break it down in more details the code example below will cover:
- Create Button programmatically in Kotlin
- Handle Button onClick events
- Change Button background color
- Change Button text color
- Add a Button in a ConstraintLayout
Using the ConstraintLayout
This example is very short and simple and thus has almost no other elements. So to be able to add and somehow position the Button within the view we will need to create an activity_button_example.xml file which contains an empty ConstraintLayout to which we will add the Button.
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/constraintLayout" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="appsdeveloperblog.kotlin.codeexamples.ButtonExample"> </android.support.constraint.ConstraintLayout>
Create Button in Kotlin. Source code.
The BottonExample.kt below is the file in which we are going to create the button programmatically and add it into the ConstraintLayout.
package appsdeveloperblog.kotlin.codeexamples import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.support.constraint.ConstraintLayout import android.widget.Button import android.graphics.Color import android.view.View class ButtonExample : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_button_example) val constraintLayout = findViewById(R.id.constraintLayout) as ConstraintLayout val button = Button(this) button.layoutParams = ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT, ConstraintLayout.LayoutParams.WRAP_CONTENT) button.text = "Click me" button.setOnClickListener(View.OnClickListener { button.text = "You just clicked me" }) button.setBackgroundColor(Color.GREEN) button.setTextColor(Color.RED) constraintLayout.addView(button); } }
You can now run your project and should be able to see a single Button with a label text on it set to “Click me” on a green background.
To learn more about Kotlin and how to use it to build native Android apps checkout the books and video courses below. They might help you to speed up your learning progress.