Wednesday, February 19, 2020

android kotlin ktx - Set and update view margin programmatically

MainActivity.kt

package com.example.jetpack

import android.content.Context
import android.os.Bundle
import android.util.TypedValue
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.*
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {

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

        // Set text view margins
        val params = textView.layoutParams as ConstraintLayout.LayoutParams
        params.setMargins(8.toDp(this))
        textView.layoutParams = params

        button.setOnClickListener {
            // Update text view end/right margin
            params.updateMarginsRelative(end = 75.toDp(this))
            textView.layoutParams = params
        }

        button2.setOnClickListener {
            // Update text view different margins
            params.updateMarginsRelative(
                50.toDp(this),
                40.toDp(this),
                30.toDp(this),
                20.toDp(this)
            )
            textView.layoutParams = params
        }
    }
}


// Extension method to convert pixels to dp
fun Int.toDp(context:Context):Int = TypedValue.applyDimension(
    TypedValue.COMPLEX_UNIT_DIP,this.toFloat(),context.resources.displayMetrics
).toInt()
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=".MainActivity">
    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:background="#CCFF00"
        android:gravity="center"
        android:text="Hello Android"
        android:padding="16dp"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textSize="35sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:backgroundTint="#E52B50"
        android:text="Update End Margin"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:backgroundTint="#333399"
        android:text="Update margins"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.501"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button" />
</androidx.constraintlayout.widget.ConstraintLayout>
build.gradle dependencies[add]

// android ktx
implementation 'androidx.core:core-ktx:1.2.0'
build.gradle [add]

android {
    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_1_8.toString()
    }
}
More android examples