Saturday, September 26, 2015

android - How to convert dp to pixels

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity"
    android:background="#fbffef"
    android:animateLayoutChanges="true"
    >
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Convert DP to Pixels"
        />
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="Sans-Serif-Condensed"
        android:textSize="17dp"
        android:layout_below="@id/btn"
        android:textStyle="italic"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.content.res.Resources;
import android.os.Bundle;
import android.app.Activity;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;

import android.widget.RelativeLayout;
import android.widget.TextView;


public class MainActivity extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the widgets reference from XML layout
        final RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
        final Button btn = (Button) findViewById(R.id.btn);
        final TextView tv = (TextView) findViewById(R.id.tv);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Create some integer values
                int dp_first = 25;
                int dp_second = 15;
                int dp_third = 29;
                int dp_fourth = 41;

                // Get the current Activity
                Activity activity = MainActivity.this;

                tv.setText("DIP/DP to Pixels conversion...\n");
                tv.setText(
                            tv.getText()+ ""+
                            dp_first+ "dp = "+ getPixelsFromDPs(activity,dp_first) + "pixels\n"
                            +dp_second+ "dp = "+ getPixelsFromDPs(activity,dp_second) + "pixels\n"
                            +dp_third+ "dp = "+ getPixelsFromDPs(activity,dp_third) + "pixels\n"
                            +dp_fourth+ "dp = "+ getPixelsFromDPs(activity,dp_fourth) + "pixels\n"
                            );
            }
        });
    }

    // Method for converting DP/DIP value to pixels
    public static int getPixelsFromDPs(Activity activity, int dps){
        /*
            public abstract Resources getResources ()

                Return a Resources instance for your application's package.
        */
        Resources r = activity.getResources();

        /*
            TypedValue

                Container for a dynamically typed data value. Primarily
                used with Resources for holding resource values.
        */

        /*
            applyDimension(int unit, float value, DisplayMetrics metrics)

                Converts an unpacked complex data value holding
                a dimension to its final floating point value.
        */

        /*
            Density-independent pixel (dp)

                A virtual pixel unit that you should use when defining UI layout,
                to express layout dimensions or position in a density-independent way.

                The density-independent pixel is equivalent to one physical pixel on
                a 160 dpi screen, which is the baseline density assumed by the system
                for a "medium" density screen. At runtime, the system transparently handles
                any scaling of the dp units, as necessary, based on the actual density
                of the screen in use. The conversion of dp units to screen pixels
                is simple: px = dp * (dpi / 160). For example, on a 240 dpi screen,
                1 dp equals 1.5 physical pixels. You should always use dp
                units when defining your application's UI, to ensure proper
                display of your UI on screens with different densities.
        */

        /*
            public static final int COMPLEX_UNIT_DIP

                TYPE_DIMENSION complex unit: Value is Device Independent Pixels.
                Constant Value: 1 (0x00000001)
        */
        int  px = (int) (TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, dps, r.getDisplayMetrics()));
        return px;
    }
}
More android examples