Wednesday, February 21, 2018

android kotlin - Convert dp to px to dp

MainActivity.kt

package com.cfsuman.kotlinexamples

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import android.util.TypedValue
import android.app.Activity
import android.content.Context
import java.util.*
import android.util.DisplayMetrics


class MainActivity : AppCompatActivity() {

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

        // Set a click listener for button widget
        button.setOnClickListener{
            val random:Random = Random()
            val value = random.nextInt(100)

            text_view.text = "Random number : $value \n\n" +
                    "Screen density : ${getScreenDensity(this)}\n\n" +
                    "$value dps = ${dpsToPixels(this,value)} pixels\n" +
                    "$value pixels = ${pixelsToDps(this,value)} dps\n" +
                    "$value pixels = ${pixelsToActualDps(this,value)} actual dps"
        }
    }



    // Method for converting DP/DIP value to pixels
    private fun dpsToPixels(activity: Activity, dps: Int): Int {
        val r = activity.resources

        /*
            *** reference source developer.android.com ***

            applyDimension(int unit, float value, DisplayMetrics metrics)

                Converts an unpacked complex data value holding
                a dimension to its final floating point value.
        */
        return TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, dps.toFloat(), r.displayMetrics).toInt()
    }


    // Method for converting pixels value to dps
    private fun pixelsToDps(context: Context, pixels: Int): Int {
        val r = context.resources
        return Math.round(pixels / (r.displayMetrics.densityDpi / 160f))
    }


    // Method for converting Pixels value to actual DPs (return float value)
    private fun pixelsToActualDps(context: Context, pixels: Int): Float {
        /*
            *** reference source developer.android.com ***

            public DisplayMetrics getDisplayMetrics ()
                Return the current display metrics that are in effect for
                this resource object. The returned object should be treated as read-only.

                Returns
                The resource's current display metrics.
        */
        val r = context.resources

        // Math.round() return the nearest whole number
        return pixels / (r.displayMetrics.densityDpi / 160f)
    }


    // Get screen density using activity
    private fun getScreenDensity(activity: Activity): Float {
        val dm = DisplayMetrics()
        activity.windowManager.defaultDisplay.getMetrics(dm)
        // The logical density of the display.
        return dm.density
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/root_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    android:background="#e6e7e4"
    >
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="DP To Pixel To DP"
        android:textAllCaps="false"
        android:layout_marginBottom="20dp"
        />
    <TextView
        android:id="@+id/text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="25dp"
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
        android:textColor="#168ace"
        android:textStyle="bold"
        />
</LinearLayout>