I have 4 different devices:
Asus tablet, screensize 7"
Lenovo tablet, screensize 7"
HTC mobile phone, screensize 5"
HTC mobile phone, screensize 4.7"
I want to know the smallest width (sw) of my device to make a support layout for it.
I want to make a resource folder like "layout-sw600dp" but I don't know the value of the smallest width (sw).
I tried to print the sw using this code:
DisplayMetrics metrics = getResources().getDisplayMetrics();
Log.i("Density", ""+metrics.densityDpi);
but i don't know if this is the correct value.
How do I find the smallest width (sw)?
Best solution for min API 13 and above:
Configuration config = getResources().getConfiguration();
config.smallestScreenWidthDp
The last line return the SW value in dp !
Source google : http://android-developers.blogspot.fr/2011/07/new-tools-for-managing-screen-sizes.html
Here is an another easy way .
You can check the Smallest Width of the Device from Developer Options (In Android Studio Emulator & It's not found in my Real Device) .
Correction to the above answer, the right code to find the correct sw try this:
DisplayMetrics dm = getApplicationContext().getResources().getDisplayMetrics();
float screenWidth = dm.widthPixels / dm.density;
float screenHeight = dm.heightPixels / dm.density;
whichever one of screenWidth and screenHeight is smaller is your sw.
Min api 13 and above go with #Tobliug answer- best solution.
Configuration config = getResources().getConfiguration();
config.smallestScreenWidthDp;// But it requires API level 13
Below API level 13 try this answer
Create SmallWidthCalculator.java class & just copy paste this code
import android.content.Context;
import android.graphics.Point;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
public class SmallWidthCalculator {
private static SmallWidthCalculator ourInstance = new SmallWidthCalculator();
public static SmallWidthCalculator getInstance() {
return ourInstance;
}
private Context mContext;
private SmallWidthCalculator() {
}
public double getSmallWidth(Context context) {
mContext = context;
DisplayMetrics dm = context.getResources().getDisplayMetrics();
int width = dm.widthPixels;
int height = dm.heightPixels;
double dpi = getDPI(width, height);
double smallWidthDPI = 0;
int smallWidth = 0;
if (width < height)
smallWidth = width;
else
smallWidth = height;
smallWidthDPI = smallWidth / (dpi / 160);
return smallWidthDPI;
}
private double getDPI(int width,
int height) {
double dpi = 0f;
double inches = getScreenSizeInInches(width, height);
dpi = Math.sqrt(Math.pow(width, 2) + Math.pow(height, 2)) / inches;
return dpi;
}
private double getScreenSizeInInches(int width, int height) {
if (mContext != null) {
DisplayMetrics dm = mContext.getResources().getDisplayMetrics();
double wi = (double) width / (double) dm.xdpi;
double hi = (double) height / (double) dm.ydpi;
double x = Math.pow(wi, 2);
double y = Math.pow(hi, 2);
return Math.sqrt(x + y);
}
return 0;
}
}
From your activity or Fragment just pass your context and get your small Width
double smallWidthDp=SmallWidthCalculator.getInstance().getSmallWidth(this);
you can try this:
DisplayMetrics dm = mActivity.getApplicationContext()
.getResources().getDisplayMetrics();
float screenWidth = dm.widthPixels / dm.xdpi;
float screenHeight = dm.heightPixels / dm.ydpi;
For Details :here
Related
I have to support android devices with screen resolution 1280*800(in dp)(KitKat) and 1280 * 752(dp)(Lollipop). The first one is a 10.1 inch tablet and second one is 9.6 inch tablet.
I am using same layout for all device and using externalized dimension to adjust layout for different screen.
But I am not able to separate the device using "values-sw720dp" and "values-sw800dp". If I use sw800dp both of them use the dimen value from sw800dp dimen folder.
How can I give separate dimension for the two devices?
Get your device's screnn inches programmatically and appy dimension
public static double getDeviceInches(Activity activity) {
DisplayMetrics metrics = getMetrics(activity);
int widthPixels = metrics.widthPixels;
int heightPixels = metrics.heightPixels;
float widthDpi = metrics.xdpi;
float heightDpi = metrics.ydpi;
float widthInches = widthPixels / widthDpi;
float heightInches = heightPixels / heightDpi;
return getDiagonalInches(widthInches, heightInches);
}
private static double getDiagonalInches(float widthInches, float heightInches) {
double diagonalInches = Math.sqrt((widthInches * widthInches) + (heightInches * heightInches));
float roundedValue = (float) Math.round(diagonalInches);
return (double)roundedValue;
}
//From this, we can get the information required to size the display:
private static DisplayMetrics getMetrics(Activity activity) {
DisplayMetrics metrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
return metrics;
}
public static int convertDpToPx(Context context, int value) {
// Get the screen's density scale
final float scale = context.getResources().getDisplayMetrics().density;
// Convert the dps to pixels, based on density scale(0.5f is for rounding up value) (arrowWidth is 50dp)
int pxValue= (int) (value * scale + 0.5f);
return pxValue;
}
Put your above code in utility class and call getDeviceInches method from your acitivty or fragment class
I need to code the layout of the android widgets using dip/dp (in java files). At runtime if I code,
int pixel=this.getWindowManager().getDefaultDisplay().getWidth();
this return the screen width in pixels (px). To convert this to dp, I coded:
int dp =pixel/(int)getResources().getDisplayMetrics().density ;
This does not seem to be returning correct answer. I made the emulator of WVGA800 whose screen resolution is 480 by 800. When the run the emulator and let the code print the values of pixel and dp, it came to 320 in both. This emulator is 240 dpi whose scale factor would be 0.75.
As #Tomáš Hubálek mentioned;
Try something like:
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
OR
Try old answer:
Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics ();
display.getMetrics(outMetrics);
float density = getResources().getDisplayMetrics().density;
float dpHeight = outMetrics.heightPixels / density;
float dpWidth = outMetrics.widthPixels / density;
I stumbled upon this question from Google, and later on I found an easy solution valid for API >= 13.
For future references:
Configuration configuration = yourActivity.getResources().getConfiguration();
int screenWidthDp = configuration.screenWidthDp; //The current width of the available screen space, in dp units, corresponding to screen width resource qualifier.
int smallestScreenWidthDp = configuration.smallestScreenWidthDp; //The smallest screen size an application will see in normal operation, corresponding to smallest screen width resource qualifier.
See Configuration class reference
Edit: As noted by Nick Baicoianu, this returns the usable width/height of the screen (which should be the interesting ones in most uses). If you need the actual display dimensions stick to the top answer.
2023 Answer simplified for Kotlin:
val widthDp = resources.displayMetrics.run { widthPixels / density }
val heightDp = resources.displayMetrics.run { heightPixels / density }
As one-liner:
val (height, width) = resources.displayMetrics.run { heightPixels/density to widthPixels/density }
For Jetpack Compose:
val (height, width) = LocalConfiguration.current.run { screenHeightDp.dp to screenWidthDp.dp }
How about using this instead ?
final DisplayMetrics displayMetrics=getResources().getDisplayMetrics();
final float screenWidthInDp=displayMetrics.widthPixels/displayMetrics.density;
final float screenHeightInDp=displayMetrics.heightPixels/displayMetrics.density;
You are missing default density value of 160.
2 px = 3 dip if dpi == 80(ldpi), 320x240 screen
1 px = 1 dip if dpi == 160(mdpi), 480x320 screen
3 px = 2 dip if dpi == 240(hdpi), 840x480 screen
In other words, if you design you layout with width equal to 160dip in portrait mode, it will be half of the screen on all ldpi/mdpi/hdpi devices(except tablets, I think)
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int width_px = Resources.getSystem().getDisplayMetrics().widthPixels;
int height_px =Resources.getSystem().getDisplayMetrics().heightPixels;
int pixeldpi = Resources.getSystem().getDisplayMetrics().densityDpi;
int width_dp = (width_px/pixeldpi)*160;
int height_dp = (height_px/pixeldpi)*160;
Answer in kotlin:
context?.let {
val displayMetrics = it.resources.displayMetrics
val dpHeight = displayMetrics.heightPixels / displayMetrics.density
val dpWidth = displayMetrics.widthPixels / displayMetrics.density
}
In the new world of Compose on one line
val (height, width) = LocalConfiguration.current.run { screenHeightDp.dp to screenWidthDp.dp }
Get Screen Width and Height in terms of DP with some good decoration:
Step 1: Create interface
public interface ScreenInterface {
float getWidth();
float getHeight();
}
Step 2: Create implementer class
public class Screen implements ScreenInterface {
private Activity activity;
public Screen(Activity activity) {
this.activity = activity;
}
private DisplayMetrics getScreenDimension(Activity activity) {
DisplayMetrics displayMetrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
return displayMetrics;
}
private float getScreenDensity(Activity activity) {
return activity.getResources().getDisplayMetrics().density;
}
#Override
public float getWidth() {
DisplayMetrics displayMetrics = getScreenDimension(activity);
return displayMetrics.widthPixels / getScreenDensity(activity);
}
#Override
public float getHeight() {
DisplayMetrics displayMetrics = getScreenDimension(activity);
return displayMetrics.heightPixels / getScreenDensity(activity);
}
}
Step 3: Get width and height in activity:
Screen screen = new Screen(this); // Setting Screen
screen.getWidth();
screen.getHeight();
This is a copy/pastable function to be used based on the previous responses.
/**
* #param context
* #return the Screen height in DP
*/
public static float getHeightDp(Context context) {
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
return dpHeight;
}
/**
* #param context
* #return the screnn width in dp
*/
public static float getWidthDp(Context context) {
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
return dpWidth;
}
If you just want to know about your screen width, you can just search for "smallest screen width" in your developer options. You can even edit it.
Your problem is with casting the float to an int, losing precision. You should also multiply with the factor and not divide.
Do this:
int dp = (int)(pixel*getResources().getDisplayMetrics().density);
I have a view and I am measuring screen size of the device dynamically using this method.
private double getscreenSize() {
DisplayMetrics dm = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
double x = Math.pow(
((double) (dm.widthPixels) / (double) (dm.densityDpi)), 2);
double y = Math.pow(
((double) (dm.heightPixels) / (double) (dm.densityDpi)), 2);
return Math.sqrt(x + y);
}
It returns 4.58 inch for both s3 and s4. But in s4 , the view looks too small and in s3 it looks perfect.
Use this code-
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int width = metrics.widthPixels;
After getting height and width use this for your view.
I have two android device with same resolution
Device1 -> resolution 480x800 diagonal screen size -> 4.7 inches
Device2 -> resolution 480x800 diagonal screen size -> 4.0 inches
How to find device diagonal screen size?
Detect 7 inch and 10 inch tablet programmatically
I have used the above link but it gives both device diagonal screen size -> 5.8
try this code to get screen size in inch
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width=dm.widthPixels;
int height=dm.heightPixels;
double wi=(double)width/(double)dm.xdpi;
double hi=(double)height/(double)dm.ydpi;
double x = Math.pow(wi,2);
double y = Math.pow(hi,2);
double screenInches = Math.sqrt(x+y);
This won't work?
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
double x = Math.pow(dm.widthPixels / dm.xdpi, 2);
double y = Math.pow(dm.heightPixels / dm.ydpi, 2);
double screenInches = Math.sqrt(x + y);
Log.d("debug", "Screen inches : " + screenInches);
Don't forget to multiply the screen size by the scaledDensity if you are doing what I did and change the size of stuff based on the screen size. e.g.:
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
double x = Math.pow(dm.widthPixels / dm.xdpi, 2);
double y = Math.pow(dm.heightPixels / dm.ydpi, 2);
double screenInches = Math.sqrt(x + y) * dm.scaledDensity;
Log.d("debug", "Screen inches : " + screenInches);
Note the second last line! Here's more info the scaledDensity stuff: What does DisplayMetrics.scaledDensity actually return in Android?
None of the above answers gave correct screen size... But the below method does it right.
private String getScreenSize() {
Point point = new Point();
((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRealSize(point);
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
int width=point.x;
int height=point.y;
double wi=(double)width/(double)displayMetrics.xdpi;
double hi=(double)height/(double)displayMetrics.ydpi;
double x = Math.pow(wi,2);
double y = Math.pow(hi,2);
return String.valueOf(Math.round((Math.sqrt(x+y)) * 10.0) / 10.0);
}
Note: This works only on API 17 & above.
Try this:
public static Boolean isTablet(Context context) {
if ((context.getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE) {
return true;
}
return false;
}
DisplayMetrics displayMetrics = context.getResources()
.getDisplayMetrics();
String screenWidthInPix = displayMetrics.widthPixels;
String screenheightInPix = displayMetrics.heightPixels;
Pythagoras theorem to find the diagonal size of Android phone/tablet screen, same principal can be applied to iPhone or Blackberry screen.
Try as below the other way:
DisplayMetrics met = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(met);// get display metrics object
String strSize =
new DecimalFormat("##.##").format(Math.sqrt(((met.widthPixels / met.xdpi) *
(met.widthPixels / met.xdpi)) +
((met.heightPixels / met.ydpi) * (met.heightPixels / met.ydpi))));
// using Dots per inches with width and height
I need to code the layout of the android widgets using dip/dp (in java files). At runtime if I code,
int pixel=this.getWindowManager().getDefaultDisplay().getWidth();
this return the screen width in pixels (px). To convert this to dp, I coded:
int dp =pixel/(int)getResources().getDisplayMetrics().density ;
This does not seem to be returning correct answer. I made the emulator of WVGA800 whose screen resolution is 480 by 800. When the run the emulator and let the code print the values of pixel and dp, it came to 320 in both. This emulator is 240 dpi whose scale factor would be 0.75.
As #Tomáš Hubálek mentioned;
Try something like:
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
OR
Try old answer:
Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics ();
display.getMetrics(outMetrics);
float density = getResources().getDisplayMetrics().density;
float dpHeight = outMetrics.heightPixels / density;
float dpWidth = outMetrics.widthPixels / density;
I stumbled upon this question from Google, and later on I found an easy solution valid for API >= 13.
For future references:
Configuration configuration = yourActivity.getResources().getConfiguration();
int screenWidthDp = configuration.screenWidthDp; //The current width of the available screen space, in dp units, corresponding to screen width resource qualifier.
int smallestScreenWidthDp = configuration.smallestScreenWidthDp; //The smallest screen size an application will see in normal operation, corresponding to smallest screen width resource qualifier.
See Configuration class reference
Edit: As noted by Nick Baicoianu, this returns the usable width/height of the screen (which should be the interesting ones in most uses). If you need the actual display dimensions stick to the top answer.
2023 Answer simplified for Kotlin:
val widthDp = resources.displayMetrics.run { widthPixels / density }
val heightDp = resources.displayMetrics.run { heightPixels / density }
As one-liner:
val (height, width) = resources.displayMetrics.run { heightPixels/density to widthPixels/density }
For Jetpack Compose:
val (height, width) = LocalConfiguration.current.run { screenHeightDp.dp to screenWidthDp.dp }
How about using this instead ?
final DisplayMetrics displayMetrics=getResources().getDisplayMetrics();
final float screenWidthInDp=displayMetrics.widthPixels/displayMetrics.density;
final float screenHeightInDp=displayMetrics.heightPixels/displayMetrics.density;
You are missing default density value of 160.
2 px = 3 dip if dpi == 80(ldpi), 320x240 screen
1 px = 1 dip if dpi == 160(mdpi), 480x320 screen
3 px = 2 dip if dpi == 240(hdpi), 840x480 screen
In other words, if you design you layout with width equal to 160dip in portrait mode, it will be half of the screen on all ldpi/mdpi/hdpi devices(except tablets, I think)
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int width_px = Resources.getSystem().getDisplayMetrics().widthPixels;
int height_px =Resources.getSystem().getDisplayMetrics().heightPixels;
int pixeldpi = Resources.getSystem().getDisplayMetrics().densityDpi;
int width_dp = (width_px/pixeldpi)*160;
int height_dp = (height_px/pixeldpi)*160;
Answer in kotlin:
context?.let {
val displayMetrics = it.resources.displayMetrics
val dpHeight = displayMetrics.heightPixels / displayMetrics.density
val dpWidth = displayMetrics.widthPixels / displayMetrics.density
}
In the new world of Compose on one line
val (height, width) = LocalConfiguration.current.run { screenHeightDp.dp to screenWidthDp.dp }
Get Screen Width and Height in terms of DP with some good decoration:
Step 1: Create interface
public interface ScreenInterface {
float getWidth();
float getHeight();
}
Step 2: Create implementer class
public class Screen implements ScreenInterface {
private Activity activity;
public Screen(Activity activity) {
this.activity = activity;
}
private DisplayMetrics getScreenDimension(Activity activity) {
DisplayMetrics displayMetrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
return displayMetrics;
}
private float getScreenDensity(Activity activity) {
return activity.getResources().getDisplayMetrics().density;
}
#Override
public float getWidth() {
DisplayMetrics displayMetrics = getScreenDimension(activity);
return displayMetrics.widthPixels / getScreenDensity(activity);
}
#Override
public float getHeight() {
DisplayMetrics displayMetrics = getScreenDimension(activity);
return displayMetrics.heightPixels / getScreenDensity(activity);
}
}
Step 3: Get width and height in activity:
Screen screen = new Screen(this); // Setting Screen
screen.getWidth();
screen.getHeight();
This is a copy/pastable function to be used based on the previous responses.
/**
* #param context
* #return the Screen height in DP
*/
public static float getHeightDp(Context context) {
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
return dpHeight;
}
/**
* #param context
* #return the screnn width in dp
*/
public static float getWidthDp(Context context) {
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
return dpWidth;
}
If you just want to know about your screen width, you can just search for "smallest screen width" in your developer options. You can even edit it.
Your problem is with casting the float to an int, losing precision. You should also multiply with the factor and not divide.
Do this:
int dp = (int)(pixel*getResources().getDisplayMetrics().density);