android detect device width

499 views Asked by At

is there a way to detect device width so that we can add views programmatically based on device screen width. For example, single or dual pane.

Right now, the way for adpative UI is using layout XML for different device size. This is not flexible enough in our case.

layout-small/
layout-large/
layout-sw600dp/

The preferred way for us is: layout.xml defines the root empty container only, and add views programmatically based on device size that is detected at runtime.

Thanks.

3

There are 3 answers

1
Athul On

U can use this code to get runtime Device's display Width & Height

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

U can set like

view.setLayoutParams(new LayoutParams(width, height));
0
MdFazlaRabbiOpu On

This code will support all version of android device Resolution(Width, Height) accurately at runtime

private void calculateDeviceResolution(Activity context) {
        Display display = context.getWindowManager().getDefaultDisplay();

        if (Build.VERSION.SDK_INT >= 17) {
            //new pleasant way to get real metrics
            DisplayMetrics realMetrics = new DisplayMetrics();
            display.getRealMetrics(realMetrics);
            realWidth = realMetrics.widthPixels;
            realHeight = realMetrics.heightPixels;

        } else if (Build.VERSION.SDK_INT >= 14) {
            //reflection for this weird in-between time
            try {
                Method mGetRawH = Display.class.getMethod("getRawHeight");
                Method mGetRawW = Display.class.getMethod("getRawWidth");
                realWidth = (Integer) mGetRawW.invoke(display);
                realHeight = (Integer) mGetRawH.invoke(display);
            } catch (Exception e) {
                //this may not be 100% accurate, but it's all we've got
                realWidth = display.getWidth();
                realHeight = display.getHeight();
                Constants.errorLog("Display Info", "Couldn't use reflection to get the real display metrics.");
            }

        } else {
            //This should be close, as lower API devices should not have window navigation bars
            realWidth = display.getWidth();
            realHeight = display.getHeight();
        }
    }

after getting the width or height you can set like this

view.setLayoutParams(new LayoutParams(realWidth , realHeight ));
0
Salaudeen Abdulrahman On

In an activity,

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

In a fragment,

DisplayMetrics dm = new DisplayMetrics();
((Activity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(dm);
int height = dm.heightPixels;
int width = dm.widthPixels;