Sunday, July 26, 2020

android kotlin - TextView 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 kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {

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

        val context = this

        val string = "Lorem Ipsum is simply dummy text of the printing" +
                " and typesetting industry."

        textView.text = string

        // set text view layout margin programmatically
        (textView.layoutParams as ConstraintLayout.LayoutParams).apply {
            // individually set text view any side margin
            marginStart = 25.dpToPixels(context)
            topMargin = 35.dpToPixels(context)
            marginEnd = 50.dpToPixels(context)

            // or set margins in this way
            /*setMargins(
                25.dpToPixels(context), // left/start margin
                35.dpToPixels(context), // top margin
                50.dpToPixels(context), // right/end margin
                0 // bottom margin
            )*/
        }
    }
}


// extension function to convert dp to equivalent pixels
fun Int.dpToPixels(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:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#EDEAE0"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:background="#DC143C"
        android:textColor="#FFFDD0"
        tools:text="Sample TextView"
        android:textSize="30sp"
        android:padding="25dp"
        android:textStyle="italic"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>