android kotlin - TextView margin programmatically

Adding Margins to a TextView Programmatically in Kotlin

This code demonstrates how to programmatically add margins to a TextView in an Android application written in Kotlin. It achieves this by modifying the TextView's layout parameters within the onCreate method of the activity.

Breakdown:

  1. Setting Up:

    • The code defines a MainActivity class that extends AppCompatActivity.
    • It retrieves the layout from the activity_main.xml file using setContentView.
    • A sample string is assigned to the textView variable.
  2. Adding Margins Programmatically:

    • The code retrieves the current layout parameters of the textView using a cast to ConstraintLayout.LayoutParams.
    • It then utilizes the apply function to modify the margins directly within the lambda expression.
    • Two approaches are presented:
      • Individually setting each margin using properties like marginStart, topMargin, and marginEnd.
      • Using a single setMargins method with values for left/start, top, right/end, and bottom margins. (Note: bottom margin is set to 0 in this example)
  3. Converting dp to Pixels:

    • The code defines an extension function dpToPixels that converts a provided integer value in dp (density-independent pixels) to its equivalent pixel value based on the device's display metrics.
  4. Layout File (activity_main.xml):

    • This file defines the layout for the activity using a ConstraintLayout.
    • Inside the layout, a TextView element with the ID textView is defined with some initial properties like width, height, background color, text color, text size, padding, and text style. Constraint properties are also set to position the text view within the layout.

Summary:

This code provides a flexible approach to programmatically adding margins to a TextView in an Android app. It demonstrates both individual margin setting and using the setMargins method. The included extension function ensures consistent conversion from dp units to pixels for different screen densities.


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>
More android kotlin tutorials