How do I obtain screen resolution information? - android

I need to obtain the screen resolution, width & height, how do I do that?
Solution:
Display d = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
width = d.getWidth();
height = d.getHeight();

Display d=Display.getInstance();
int width = d.getDisplayWidth();
int height = d.getDisplayHeight();
According to http://forums.java.net/jive/message.jspa?messageID=479230
or possibly
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int width = display.getWidth();
http://www.coderanch.com/t/435390/Android/Mobile/screen-size-at-run-time

PLEASE first ask yourself why you need to do this. You very probably don't. If it is to do anything based on the screen size (layout etc) this will return you the wrong information, since it is telling you about the physical resolution of the screen, not taking into account anything like the status bar, window decorations, etc. Even if you are running your app as full-screen, in some cases there may be parts of the screen that are used for system UI that you can't get rid of but will be included in the numbers returned by Display.
The correct thing to do is adjust for the size your view gets during layout, such as when its onSizeChanged() is called.

Related

Get screen size in Android

It seems in Android there are two ways to get screen width & height:
The 1st way:
WindowManager windowManager =
(WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
//We get width and height in pixels here
width = size.x;
height = size.y;
The 2nd way is:
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
//We get width and height in pixels here
int width = metrics.widthPixels;
int height = metrics.heightPixels;
Both ways get screen width and height in pixels. So, I get a bit confused about the following two questions:
Q1. What are the differences between these two screen sizes theoritically?
Q2. Why google provide two ways to get screen size? I think there must be a reason behind it.
You should read about those two Classes
Window Manager
http://developer.android.com/reference/android/view/WindowManager.html
Resources
http://developer.android.com/reference/android/content/res/Resources.html
Window Manager gets screen width and height by getting the width and height of display that the window manager instance is managing including secondary display.
Getting width and height from Resources return the current display metrics and the objects should be treated as Read Only.
looking at the docs about DisplayMetrics:
A structure describing general information about a display, such as
its size, density, and font scaling.
It seems that the DisplayMetrics class provides you with basic hardware display information. It does not care about any system UI components that may (or may not) be present.
While the Display class is more extended and takes the things mentioned above into account.
To answer your question:
int width = metrics.widthPixels;
int height = metrics.heightPixels;
will provide you with absolute values, i.e. you will always get 1080/1920 on a full HD display.
The description of the getSize() method is pretty much self-explanatory:
[...] The size returned by this method does not necessarily represent
the actual raw size (native resolution) of the display. The returned
size may be adjusted to exclude certain system decoration elements
that are always visible. [...]
DisplayMetrics is a data object which best describes the details of the current display, including widthPixels, heightPixels, xDpi, yDpi, density, densityDpi and scaledDensity.
Display is a more logical object which performs the logical operations behind finding these parameters. For example, Display can be used to extract DisplayMetrics like so:
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics); // metrics will now be populated with the required data.
Note: The above code is, in essence, how Android generates the DisplayMetrics instance inside the Resources object.
I most often use DisplayMetrics, but both options should work just fine.

Layout stretching

Is there a layout, that would allow me to make it in absolute values, but when it would be on larger / smaller screen, it would stretch and adjusted those values, to fit onto the screen but preserve the same look?
Relative layout still keens on exact values.
For example, I have a button and I want it to have it the width of 1/3 of the screen of every device.
Setting manualy in code the width of an element to (for example) screenWidth/3 works. Yet I don't think it's clean. But this technique works.
Find device dimensions at runtime and set width of button at runtime.
Display mDisplay = getWindowManager().getDefaultDisplay();
int deviceWidth = mDisplay.getWidth();
int deviceHeight = mDisplay.getHeight();
button.getLayoutParams().width = deviceWidth / 3;
Give the values in dpi of your layout and view and they will adjust themselves on any screen

how to get android screen size programmatically, once and for all?

How can I find out my screen size programmatically,
in the units used by touch events
and View measurement/layout?
In other words, I want the coordinates
of the bottom-right corner of the screen,
in the coordinate system used by touch events'
getRawX()/getRawY() and View.getLocationOnScreen().
I'm hesitant to call the desired event/view units "pixels"
since evidently there are several notions of "pixels"
on my phone in various modes,
and they're not adding up to a consistent story.
I see this has been asked and answered a lot
on stackoverflow and elsewhere,
but none of the answers actually work on my phone
(droid 4, android 4.1.2) in all modes:
Can I find out width of screen programmatically in android app?
How do I get the ScreenSize programmatically in android
Android set View visibility programmatically based on screen size
How do I get the height of the screen in Android?
Get the screen height in Android
https://groups.google.com/forum/#!topic/android-developers/IpxnfvDFrpc
http://shuklaxyz.blogspot.com/2012/02/how-to-programmatically-figure-out.html
http://coderock.net/how-to-determine-screen-resolution-programmatically/
http://www.codeproject.com/Tips/313848/Get-actual-screen-size-for-the-application-layout
Android and setting width and height programmatically in dp units
http://www.simplecodestuffs.com/how-to-get-screen-dimensions-programmatically-in-android/
http://www.androidsnippets.com/get-size-and-orientation-of-the-screen
http://grokbase.com/t/gg/android-developers/127aatfqb6/how-to-determine-screen-resolution-programmatically
(wow!)
This is for library code that needs to work
regardless of whether the app is in "screen compatibility mode"
(i.e. targetSdkVersion<=10 in the manifest) or not,
and I also don't want to make any assumptions
about the position, size, or existence of the status bar
or any other similar screen decorations.
Here are the facts:
my phone (a droid 4 running android 4.1.2)
has 540x960 physical pixels,
i.e. little colored glowing dots.
the size of the screen in the desired units,
from looking at touch events and View measurements, is
360x640 when the app is in screen compat mode,
540x960 when the app is not in screen compat mode.
These are the numbers I need to find programmatically,
without mucking with touch events or Views to find them,
but I'm having extreme difficulty finding any API
that will return these numbers.
Display and DisplayMetrics objects obtained
in various ways all claim the screen size
is 540x960 "pixels"
(whether in screen compat mode or not).
To be specific, the following all say 540x960 all the time:
DisplayMetrics.{width,height}Pixels,
Display.getSize(),
Display.getRealSize(),
Display.get{Width,Height}(),
Configuration objects obtained in various ways
all say screen{Width,Height}Dp = 360x614
(whether in screen compat mode or not).
I don't believe that represents the whole screen,
since the aspect ratio is wrong.
(I think it's the whole screen
minus the status bar; I need the whole screen.)
I think it's safe to say that the whole screen is 360x640 dp,
though I don't know any API that returns that 640.
DisplayMetrics obtained in various ways
say the "density" is
1.0f when in screen compat mode,
1.5f when not in screen compat mode.
The activity's
getWindow().getAttributes().{width,height}
isn't helpful since it typically contains MATCH_PARENT
rather than actual sizes.
But I can apparently get the desired answer from an activity's
getWindow().getDecorView().getMeasured{Width,Height}()
(which is actually surprising since
the activity's window's decorView
doesn't look like it's taking up the whole screen;
it looks like it's taking up the screen minus the status bar).
But I don't want to rely on this because if the window ever gets resized
(soft keyboard appearing? someone calling window.setAttributes()?
or maybe I'm not in an Activity at all),
this is clearly going to be all wrong.
I understand the following formula is supposed to hold:
pixels = dp * density
That seems to agree with all the reported numbers ((3),(4),(5) above)
when not in screen compatibility mode:
540x960 = 360x640 * 1.5
But in screen compatibility mode it doesn't add up:
540x960 != 360x640 * 1
So, something is awry.
The simplest explanation, I think,
is that the methods listed in (3) above
are simply giving the wrong answer for "pixels" when
in screen compat mode-- that is, they were intended
to return 360x640 "pixels" but they are wrongly returning 540x960 instead.
But there may be other ways of looking at it.
In any case, getting the desired numbers regardless of mode,
from the above puzzle pieces, is certainly a tricky puzzle.
I have found a way that seems to work on my phone in both modes,
but it is extremely circuitous,
and it relies on two assumptions that still seem rather shaky
(as described in the code comments below).
Here is my recipe:
/** get screen size in "pixels", i.e. touchevent/view units.
* on my droid 4, this is 360x640 or 540x960
* depending on whether the app is in screen compatibility mode
* (i.e. targetSdkVersion<=10 in the manifest) or not. */
public void getScreenSizePixels(int widthHeightInPixels[/*2*/])
{
Resources resources = getResources();
Configuration config = resources.getConfiguration();
DisplayMetrics dm = resources.getDisplayMetrics();
// Note, screenHeightDp isn't reliable
// (it seems to be too small by the height of the status bar),
// but we assume screenWidthDp is reliable.
// Note also, dm.widthPixels,dm.heightPixels aren't reliably pixels
// (they get confused when in screen compatibility mode, it seems),
// but we assume their ratio is correct.
double screenWidthInPixels = (double)config.screenWidthDp * dm.density;
double screenHeightInPixels = screenWidthInPixels * dm.heightPixels / dm.widthPixels;
widthHeightInPixels[0] = (int)(screenWidthInPixels + .5);
widthHeightInPixels[1] = (int)(screenHeightInPixels + .5);
}
Is there any better/cleaner way
to find the size of the screen??
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
Now you can measure your screen size in pixel which is a better measurement unit than centimeter because all the buttons ,textviews etc.. are measured in this unit. That what I use normally
By using the DisplayMetrics you can get height and width of the screen of any device. Note that width and height are sensitive to rotation.
here is the code.
DisplayMetrics metrics;
int width = 0, height = 0;
In your onCreate Method
metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
height = Math.min(metrics.widthPixels, metrics.heightPixels); //height
width = Math.max(metrics.widthPixels, metrics.heightPixels); //width
Try this.
In your #6, you note that the DecorView seems to provide what you want, but you don't think it is realiable. I believe that is as close as you can come. According to the documentation for Window.getDecorView:
Retrieve the top-level window decor view (containing the standard window frame/decorations and the client's content inside of that), which can be added as a window to the window manager.
The status bar is part of the window decoration mentioned there. Software keyboards and other overlays will receive their own window, so they shouldn't interfere with the relevant values. It is correct that isn't precisely the display metrics, but if your application is full screen it should always be the full screen size filtered through the compatibility translator. Other applications won't have access to your application's Window, so there is no need to worry about some other app changing the attributes while you aren't looking.
Hope that helps.
I should put this as a comment but I don't have the rep for that.
This may not be a totally correct answer but I got my dimensions when I switched the height and width in the DisplayMetrics method.
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
width = metrics.heightPixels;
height = metrics.widthPixels;
as I said this may not be correct but I don't know why but it worked for me.
If you are using api level 17 or higher check out getRealMetrics and getRealSize in Display
For api level 14,15 & 16 look here
I've used Pythagoras theorem to find the diagonal size of Android phone/tablet screen, same principal can be applied to iPhone or Blackberry screen.
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
Pythagoras must have been a genios, he knew smart phone programming so many years ago :p
I use the below method to get the width of the device :
public static int getDeviceWidth(Context context){
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
int width=display.getWidth();
return width;
}
I think this function will help you to simply get the width and height of your android screen size. The function returns the width and height as an array of integers as shown below
private int[] getScreenSIze(){
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int h = displaymetrics.heightPixels;
int w = displaymetrics.widthPixels;
int[] size={w,h};
return size;
}
and on your create method output your width and height as shown below
int[] screenSize= getScreenSIze();
int width=screenSize[0];
int height=screenSize[1];
screenSizes.setText("Phone Screen sizes \n\n width = "+width+" \n Height = "+height);
Download source code and test it on your android studio
This works for me:
int width = Resources.getSystem().getDisplayMetrics().widthPixels;
int height = Resources.getSystem().getDisplayMetrics().heightPixels;
I used this to update width of my items in a horizontal recycler view.(according to my requirement)
Hope it helps someone!
For this solution in Kotlin, try this:
private fun yourFunction(){
val metrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(metrics)
val width = metrics.widthPixels
val height = metrics.heightPixels
}

Disable ImageView if it doesn't fit on the screen

I have an ImageView with a dynamic src, and I want to display it, only if there is enough place to show all of it without scaling it.
How should I handle this?
you need to get the image size and screen size then check to see if its larger before displaying
If you want the the display dimensions in pixels you can use
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
If you don't have access to an activity to call getWindowManager on. You can use:
Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
For the use case you're describing however a margin/padding in the layout seems more appropriate.
then do
if (ImageView.getDrawable().getIntrinsicHeight() > height || ImageView.getDrawable().getIntrinsicWidth() >width){
//dont display image
}
coppied and compiled from two post
Get screen dimensions in pixels
and
Trying to get the display size of an image in an ImageView
imageView.setScaleType(ScaleType.FIT_XY);

Unable to get the correct screen size using Services for Android

So i am trying to get the screen size of the Moto Droid on my application. on my Create, i am using the Service windowManager to get the default display.
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
When i set it i get width of 320 and height 570. that looks wrong, it should be 320x480.
i want to place a 300x50 image on the bottom of the screen on any device (actually) so normally i would get the height of the screen and minus the image height so it places it on a view. but since i am getting 570 for some reason, i have to scroll down to see the image. why is it getting the wrong screen size and is there another more accurate way of getting the size. Thank you
Layout code goes as follows
linearOut = new LinearLayout(this);
linear = new LinearLayout(this);
linear.setOrientation(LinearLayout.VERTICAL);
scroll = new ScrollView(this);
linearOut.addView(scroll);
scroll.addView(linear);
linear.addView(text);
linear.addView(bbottom.getViewGroup());
setContentView(linearOut);
try this::
Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
I think i got it. so the info above shows full screen viewable. so that does include the status bar. Is there a way to see the height of the status bar? i am not sure if all android devices have the same pixel height for the status bar.

Categories

Resources