Sunday, July 26, 2020

android kotlin - Create TextView programmatically

MainActivity.kt

package com.example.jetpack

import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.util.TypedValue
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintLayout.LayoutParams
import androidx.constraintlayout.widget.ConstraintLayout.LayoutParams.PARENT_ID
import androidx.constraintlayout.widget.ConstraintSet
import androidx.core.widget.TextViewCompat
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."

        createTextView().apply {
            text = string
            constraintLayout.addViewCenter(context,this)
        }
    }
}


// extension function to create a text view programmatically
fun Context.createTextView():TextView{
    return TextView(this).apply {
        text = "Sample TextView" // text

        // set text view text appearance
        TextViewCompat.setTextAppearance(
            this,
            android.R.style.TextAppearance_DeviceDefault_Large
        )

        // set text appearance or individually set styles
        typeface = Typeface.MONOSPACE // font

        background = ColorDrawable(Color.parseColor("#FFFAF0")) // background color
        setTextColor(Color.parseColor("#A2006D")) // text color

        setTypeface(typeface, Typeface.ITALIC) // text style
        setTextSize(TypedValue.COMPLEX_UNIT_SP,30F) // text size

        val padding = 25.dpToPixels(this@createTextView)
        setPadding(padding,padding,padding,padding) // padding

        // text view width and height
        layoutParams = LayoutParams(
            LayoutParams.MATCH_PARENT, // width
            LayoutParams.WRAP_CONTENT // height
        )

        // generate a view id for text view
        id = View.generateViewId()
    }
}


// extension function to add view to constraint layout center
fun ConstraintLayout.addViewCenter(context:Context, view:View){
    addView(view)

    // initialize a new constraint set
    val set = ConstraintSet()
    set.clone(this)

    val margin = 16.dpToPixels(context)

    // put view center in parent
    set.connect(view.id,ConstraintSet.START,PARENT_ID,
        ConstraintSet.START,margin)

    set.connect(view.id,ConstraintSet.TOP,PARENT_ID,ConstraintSet.TOP)

    set.connect(view.id,ConstraintSet.END,PARENT_ID,
        ConstraintSet.END,margin)

    set.connect(view.id,ConstraintSet.BOTTOM,PARENT_ID,ConstraintSet.BOTTOM)

    // finally, apply the constraint set to constraint layout
    set.applyTo(this)
}


// extension function to convert dp to 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"/>