How to Get Device Height and Width at Runtime?

前端 未结 6 359
执念已碎
执念已碎 2020-12-09 15:06

I am developing an app in which I have to make our app to fit for every device - for both tablet and android mobiles. Now I want to get the device height and width at runtim

相关标签:
6条回答
  • 2020-12-09 15:53

    In the onCreate of your activity you can do

    mScreenWidth = getActivity().getWindowManager().getDefaultDisplay().getWidth();
    
    mScreenHeight = getActivity().getWindowManager().getDefaultDisplay().getHeight();
    

    and later use these variables to access device height and width

    0 讨论(0)
  • 2020-12-09 16:00

    You can get all the display related information using the class Display Metrics http://developer.android.com/reference/android/util/DisplayMetrics.html

    you would require

    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    

    After this all the required information will be present in your metrics object.

    The other option is to call

    getActivity().getWindowManager().getDefaultDisplay().getWidth()
    getActivity().getWindowManager().getDefaultDisplay().getHeight()
    
    0 讨论(0)
  • 2020-12-09 16:02
    Display mDisplay = activity.getWindowManager().getDefaultDisplay();
    final int width  = mDisplay.getWidth();
    final int height = mDisplay.getHeight();
    

    This way you can get the screen size.

    Since this API is depricated in the new SDK versions you can use this.

    DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
    int width = displayMetrics.widthPixels;
    int height = displayMetrics.heightPixels;
    
    0 讨论(0)
  • 2020-12-09 16:03

    this is how you get the available screen dimensions. This will get you not the raw pixel size but the available space of your window/activity.

        Point outSize = new Point();
        getWindowManager().getDefaultDisplay().getSize(outSize);
    

    Also you can have different layout xml files for both landscape and portrait. Put your xml for portrait in res/layout-port. Layout for landscape can be put into res/layout-land. You should read up how android handles resources

    0 讨论(0)
  • 2020-12-09 16:04

    In a Activity scope do:

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    int w = dm.widthPixels; // etc...
    
    0 讨论(0)
  • 2020-12-09 16:05

    I'm not going to tell you how to get the screen dimensions, as everybody else here did that already. I'm pointing you to a link from the android developer dev guide, which should teach you how to design and develop for devices of different screen sizes.

    After reading, come back and tell us again that you still want to get the width and height of the screen.

    0 讨论(0)
提交回复
热议问题