Sunday, July 26, 2020

android kotlin - TextView get width height programmatically

MainActivity.kt

package com.example.jetpack

import android.os.Bundle
import android.view.View
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)

        // get first text view's width and height programmatically
        textView.getWidthHeight().apply {
            // show height and width in second text view
            textView2.text = "width $first pixels * height $second pixels"
        }
    }
}


// extension function to get a view's width and height programmatically
fun View.getWidthHeight():Pair<Int,Int>{
    // find out how big a view should be
    measure(
        // horizontal space requirements as imposed by the parent
        0, // widthMeasureSpec

        // vertical space requirements as imposed by the parent
        0 // heightMeasureSpec
    )

    // the raw measured width of this view
    val width = measuredWidth

    // the raw measured height of this view
    val height = measuredHeight

    // return view's width and height in pixels
    return Pair(width,height)
}
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="#E8CCD7"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:background="#FF007F"
        android:textColor="#FADA5E"
        android:padding="25dp"
        android:text="Measure Me"
        android:textSize="40sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        tools:text="TextView"
        style="@style/TextAppearance.AppCompat.Medium"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

</androidx.constraintlayout.widget.ConstraintLayout>