Sunday, September 27, 2015

android - How to get screen density

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="#eddf00"
    android:animateLayoutChanges="true"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="Sans-Serif-Condensed"
        android:textSize="18dp"
        android:textStyle="italic"
        android:textColor="#000000"
        android:padding="15dp"
        />
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get Screen Density"
        android:layout_below="@id/tv"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.app.ActionBar;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.util.DisplayMetrics;
import android.content.Context;
import android.view.WindowManager;


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);

        ActionBar ab = getActionBar();
        ab.setBackgroundDrawable(new ColorDrawable(Color.RED));

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*
                    Context
                        Interface to global information about an application environment.
                        This is an abstract class whose implementation is provided by the
                        Android system. It allows access to application-specific resources
                        and classes, as well as up-calls for application-level operations
                        such as launching activities, broadcasting and receiving intents, etc.
                */

                // Get the application context
                Context context = getApplicationContext();

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

                tv.setText("Screen density from activity : "
                        + getScreenDensity(activity));
                tv.setText(tv.getText() + "\nScreen density from context : "
                        + getScreenDensityFromContext(context));
           }
        });
    }

    // Custom method to get screen density using activity
    public static float getScreenDensity(Activity activity){
        /*
            DisplayMetrics
                A structure describing general information about a display,
                such as its size, density, and font scaling.
        */
        DisplayMetrics dm = new DisplayMetrics();

        /*
            WindowManager
                The interface that apps use to talk to the window manager.
                Use Context.getSystemService(Context.WINDOW_SERVICE) to get one of these.
        */

        /*
            public abstract Display getDefaultDisplay ()

                Returns the Display upon which this WindowManager instance will create new windows.

                Returns
                The display that this window manager is managing.
        */

        /*
            public void getMetrics (DisplayMetrics outMetrics)
                Gets display metrics that describe the size and density of this display.
                The size is adjusted based on the current rotation of the display.

                Parameters
                outMetrics A DisplayMetrics object to receive the metrics.
        */
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        /*
            public float density
             The logical density of the display.
        */
        float density = dm.density;
        return density;
    }

    // Custom method to get screen density using Context object
    public static float getScreenDensityFromContext(Context context){
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) context.getSystemService(WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(dm);
        /*
            public float density
                The logical density of the display. This is a scaling factor for the Density
                Independent Pixel unit, where one DIP is one pixel on an approximately
                160 dpi screen (for example a 240x320, 1.5"x2" screen), providing
                the baseline of the system's display. Thus on a 160dpi screen this
                density value will be 1; on a 120 dpi screen it would be .75; etc.
        */
        float density = dm.density;
        return density;
    }
}
More android examples