How can I get the screen width and height and use this value in:
@Override protected void onMeasure(int widthSpecId, int heightSpecId) {
Log.e(TAG, \"onM
Try this code for Kotlin
val display = windowManager.defaultDisplay
val size = Point()
display.getSize(size)
var DEVICE_WIDTH = size.x
var DEVICE_HEIGHT = size.y
There is a very simple answer and without pass context
public static int getScreenWidth() {
return Resources.getSystem().getDisplayMetrics().widthPixels;
}
public static int getScreenHeight() {
return Resources.getSystem().getDisplayMetrics().heightPixels;
}
Note: if you want the height include navigation bar, use method below
WindowManager windowManager =
(WindowManager) BaseApplication.getApplication().getSystemService(Context.WINDOW_SERVICE);
final Display display = windowManager.getDefaultDisplay();
Point outPoint = new Point();
if (Build.VERSION.SDK_INT >= 19) {
// include navigation bar
display.getRealSize(outPoint);
} else {
// exclude navigation bar
display.getSize(outPoint);
}
if (outPoint.y > outPoint.x) {
mRealSizeHeight = outPoint.y;
mRealSizeWidth = outPoint.x;
} else {
mRealSizeHeight = outPoint.x;
mRealSizeWidth = outPoint.y;
}
DisplayMetrics lDisplayMetrics = getResources().getDisplayMetrics();
int widthPixels = lDisplayMetrics.widthPixels;
int heightPixels = lDisplayMetrics.heightPixels;
public class DisplayInfo {
int screen_height=0, screen_width=0;
WindowManager wm;
DisplayMetrics displaymetrics;
DisplayInfo(Context context) {
getdisplayheightWidth(context);
}
void getdisplayheightWidth(Context context) {
wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
displaymetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(displaymetrics);
screen_height = displaymetrics.heightPixels;
screen_width = displaymetrics.widthPixels;
}
public int getScreen_height() {
return screen_height;
}
public int getScreen_width() {
return screen_width;
}
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
public static double getHeight() {
DisplayMetrics displayMetrics = new DisplayMetrics();
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
display.getRealMetrics(displayMetrics);
//int height = displayMetrics.heightPixels;
//int width = displayMetrics.widthPixels;
return displayMetrics.heightPixels;
}
Using that method you can get screen height.
if you want to get width change displayMetrics.heightPixels
to displayMetrics.widthPixels
.
And it also include required api Build version.
It’s very easy to get in Android:
int width = Resources.getSystem().getDisplayMetrics().widthPixels;
int height = Resources.getSystem().getDisplayMetrics().heightPixels;