Saturday, July 25, 2020

android kotlin - TextView add border programmatically

MainActivity.kt

package com.example.jetpack

import android.graphics.Color
import android.graphics.Paint
import android.graphics.drawable.ShapeDrawable
import android.graphics.drawable.shapes.RectShape
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {

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

        // add a border around text view
        textView.addBorder(Color.RED, 20F)
    }
}


// extension function to add border to text view programmatically
fun TextView.addBorder(
    color : Int = Color.GRAY,
    width : Float = 10F
){
    // initialize a shape drawable
    val drawable = ShapeDrawable().apply {
        // specify the shape of shape drawable
        shape = RectShape()

        paint.apply {
            // specify the border color of shape
            this.color = color

            // set the border width
            strokeWidth = width

            // specify the style is a Stroke
            style = Paint.Style.STROKE
        }
    }

    // finally, add the shape drawable background to text view
    background = drawable
}
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="wrap_content"
        android:layout_height="wrap_content"
        android:padding="25dp"
        android:text="Sample TextView"
        android:textSize="30sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>