Tuesday, March 19, 2013

How to get Device Density in Android | Get Device Resolution in Android | Get Device Height and Width of Android Device Programmatic

Hello Friends, I am sharing code for get density size, height, width of Android device. Just copy paste below code and enjoy..

Print Screen:


1)MainActivity.java

package com.example.densityproject;

import android.app.Activity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
 TextView textView;
 Button button;
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  button = (Button) findViewById(R.id.button1);
  textView = (TextView) findViewById(R.id.textView1);
  button.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    DisplayMetrics metrics = new DisplayMetrics();
    Display mDisplay = MainActivity.this.getWindowManager()
      .getDefaultDisplay();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    float screenDensity = metrics.density;
    float screenDensityDPI = metrics.densityDpi;
    int width = mDisplay.getWidth();
    int Height = mDisplay.getHeight();

    Log.e("Density:", String.valueOf(screenDensity + "---"
      + screenDensityDPI));

    textView.setText("Device Density=" + screenDensity + "Height="
      + Height + "Width=" + width);

   }
  });

 }

}

2)activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="144dp"
        android:text="Check Density" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="68dp"
       android:textSize="35sp" />
   
</RelativeLayout>
For any help or suggestion put your comment... Thanks,

No comments :

Post a Comment