How to programmatically set View margins in dp in Kotlin

In this android kotlin source code example, we are going to programmatically set margins in dp 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 set margins in dp in Kotlin

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Button.ButtonActivity13">

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/marginBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        android:textColor="#ffffff"
        android:text="Margin Button"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.kt

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.AppCompatButton
import androidx.core.content.ContextCompat
import com.bluapp.kotlinview.R

class ButtonActivity13 : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_button13)
        val marginBtn = findViewById<AppCompatButton>(R.id.marginBtn)
        setMarginsInDp(marginBtn, 25, 0, 25, 0)
    }

    fun setMarginsInDp(view: View, left: Int, top: Int, right: Int, bottom: Int){
        if(view.layoutParams is ViewGroup.MarginLayoutParams){
            val screenDesity: Float = view.context.resources.displayMetrics.density
            val params: ViewGroup.MarginLayoutParams = view.layoutParams as ViewGroup.MarginLayoutParams
            params.setMargins(left*screenDesity.toInt(), top*screenDesity.toInt(), right*screenDesity.toInt(), bottom*screenDesity.toInt())
            view.requestLayout()
        }
    }
}

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.