Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get screen width and height in a Fragment

If I extend activity in my app I can get width and height:

DisplayMetrics displaymetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); int height = displaymetrics.heightPixels; int wwidth = displaymetrics.widthPixels; 

or

Display display = getWindowManager().getDefaultDisplay();  stageWidth = display.getWidth(); stageHeight = display.getHeigth(); 

But at present I extend fragment and I can't use the above code to get the width.

like image 578
pengwang Avatar asked Jul 24 '12 11:07

pengwang


People also ask

How can get screen width and height in android programmatically?

Display display = getWindowManager(). getDefaultDisplay(); Point size = new Point(); display. getSize(size); int width = size. x; int height = size.

How do you find the width of a device?

You can get the device screen width via the screen. width property. Sometimes it's also useful to use window. innerWidth (not typically found on mobile devices) instead of screen width when dealing with desktop browsers where the window size is often less than the device screen size.


2 Answers

Try below modifed code of yours

DisplayMetrics displaymetrics = new DisplayMetrics(); getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); int height = displaymetrics.heightPixels; int width = displaymetrics.widthPixels; 

or

Display display = getActivity().getWindowManager().getDefaultDisplay();  int stageWidth = display.getWidth(); int stageHeight = display.getHeight(); 

Basically you just required to put getActivity() (to get the context) before getWindowManager() function.

like image 51
rajpara Avatar answered Oct 14 '22 01:10

rajpara


This will give you what you want without needing for context or view:

import android.content.res.Resources;  int width = Resources.getSystem().getDisplayMetrics().widthPixels;  int height = Resources.getSystem().getDisplayMetrics().heightPixels; 
like image 39
Alex Jolig Avatar answered Oct 14 '22 01:10

Alex Jolig