Wednesday, February 21, 2018

android kotlin - Convert dp to px to dp

MainActivity.kt

package com.example.jetpack

import android.app.Activity
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.util.DisplayMetrics
import android.util.TypedValue
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import kotlin.math.roundToInt
import kotlin.random.Random


class MainActivity : AppCompatActivity() {

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

        // generate random integer and float value
        val random = Random.nextInt(50,100)
        val randomFloat = Random.nextFloat() * 100

        // show the screen density
        textView.text = "Screen Density: ${displayMetrics.density}"


        // convert integer dp value to equivalent pixels value
        textView.append("\n\nRandom Number : $random")
        val pixels = random.dpToPixels(this)
        textView.append("\n$random dp = $pixels pixels (Float)")
        textView.append("\n$random dp = ${pixels.roundToInt()} pixels (Int)")


        // convert integer pixels value to equivalent dp value
        val dp = random.pixelsToDp(this)
        textView.append("\n\n$random pixels = $dp dp (Float)")
        textView.append("\n$random pixels = ${dp.roundToInt()} dp (Int)")


        // convert float pixels and dp to equivalent dp and pixels value
        textView.append("\n\nRandom Float : $randomFloat")
        textView.append("\n$randomFloat dp =" +
                " ${randomFloat.dpToPixels(this)} pixels")
        textView.append("\n$randomFloat pixels =" +
                " ${randomFloat.pixelsToDp(this)} dp")
    }
}


// extension function to convert dp to equivalent pixels
fun Int.dpToPixels(context: Context):Float = TypedValue.applyDimension(
    TypedValue.COMPLEX_UNIT_DIP,this.toFloat(),context.resources.displayMetrics
)

// input float dp value to convert equivalent pixels
fun Float.dpToPixels(context: Context):Float = TypedValue.applyDimension(
    TypedValue.COMPLEX_UNIT_DIP,this,context.resources.displayMetrics
)


// extension function to convert pixels to equivalent dp
fun Int.pixelsToDp(context: Context):Float{
    return this / (context.resources
        .displayMetrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT).toFloat()
}

// input float pixels value to convert equivalent dp
fun Float.pixelsToDp(context: Context):Float{
    return this / (context.resources
        .displayMetrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT).toFloat()
}


// extension property to get display metrics instance
val Activity.displayMetrics: DisplayMetrics
    get() {
        val displayMetrics = DisplayMetrics()

        if (Build.VERSION.SDK_INT >= 30){
            display?.apply {
                getRealMetrics(displayMetrics)
            }
        }else{
            // getMetrics() method was deprecated in api level 30
            windowManager.defaultDisplay.getMetrics(displayMetrics)
        }

        return displayMetrics
    }
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="#E5E4E2"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="32dp"
        android:layout_marginEnd="16dp"
        android:fontFamily="sans-serif-condensed"
        android:textColor="#191970"
        android:textSize="25sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:text="TextView" />

</androidx.constraintlayout.widget.ConstraintLayout>
More android examples