Error getting window size on android: “The method getWindowManager is undefined”

前端 未结 6 2232
半阙折子戏
半阙折子戏 2020-12-18 20:08

I need to get the window height and the weight.
I have this in my code:

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDispl         


        
相关标签:
6条回答
  • 2020-12-18 20:25

    You could use this for example if you are using it inside a fragment:

    getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
    
    0 讨论(0)
  • 2020-12-18 20:31

    it works for me

    import android.app.Activity;
    
    ((Activity)getContext()).getWindowManager().getDefaultDisplay().getMetrics(metrics);
    
    mediaProjectionManager = (MediaProjectionManager)((Activity) getContext()).getSystemService(Context.MEDIA_PROJECTION_SERVICE);
    
    0 讨论(0)
  • 2020-12-18 20:43

    Please check if you are calling above method in an activity class, or outside activity.

    For Wallpaper, this method is not availed to you to get height or width of window, you need to get width and height of available window by using surface.

    0 讨论(0)
  • 2020-12-18 20:47

    Where are you using this code?

    The error of the getWindowManager says that cannot find the method because the root of your class doesn't have it.

    Try this:

    ((Activity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(metrics);
    

    or

    ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
      .getDefaultDisplay().getMetrics(metrics);
    

    If this doesn't work, please paste your activity

    0 讨论(0)
  • 2020-12-18 20:47

    Use the Context of the activity with getActivityContext()

    DisplayMetrics metrics = new DisplayMetrics();
    getActivityContext().getWindowManager().getDefaultDisplay().getMetrics(metrics);
    width1 = metrics.widthPixels; 
    height1 = metrics.heightPixels;
    
    0 讨论(0)
  • 2020-12-18 20:50

    Use this:

     display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
     display.getWidth(); // to get width of the screen
     display.getHeight(); // to get height of the Screen
    

    UPDATE

    Please review the Android-Developer site. For more reference.

    You can use below snippet of code to fetch height-width of the device.

    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    int width = size.x;
    int height = size.y;
    
    0 讨论(0)
提交回复
热议问题