How to programmatically center a button in Android Kotlin

In this android kotlin programming source code example, we are going to programmatically center a button in a layout in Kotlin.

You can copy and adopt this source code example to your Kotlin android project without reinventing the wheel.

Below is a step by step source code to programmatically center a button in a layout in Kotlin.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Button.ButtonActivity6">

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/centerBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        android:textColor="#ffffff"
        android:text="Center Button" />

</RelativeLayout>

MainActivity.kt

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.appcompat.widget.AppCompatButton
import com.bluapp.kotlinview.R
import android.widget.RelativeLayout
import android.view.ViewGroup



class ButtonActivity6 : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_button6)
        val centerBtn = findViewById<AppCompatButton>(R.id.centerBtn);
        val centerRel = RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        centerRel.setMargins(10, 10, 10, 10)
        centerRel.addRule(RelativeLayout.CENTER_IN_PARENT)
        centerBtn.setLayoutParams(centerRel)

    }
}

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.