简体   繁体   English

在Android中使用WindowManager时类强制转换异常

[英]Class cast exception while using WindowManager in Android

My code to get the screen height dynamically: 我动态获取屏幕高度的代码:

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

Error: Error: java.lang.ClassCastException: android.app.Application Complete log cat: http://pastebin.com/8zUNFUYn 错误:错误:java.lang.ClassCastException:android.app.Application完成日志cat: http//pastebin.com/8zUNFUYn

Edit: Changed code to this: 编辑:将代码更改为:

Display display =  (activity).getWindowManager().getDefaultDisplay();

        Point size = new Point();
        display.getSize(size);
        int width = size.x;
        int height = size.y;

Worked but, gave a new error that is display.getSize(size) is not a method. 工作但是,给出了一个新的错误,即display.getSize(size)不是一个方法。 Is that API depreceated? 该API是否已被删除?

Context 上下文

is base class for both Application and Activity. 是Application和Activity的基类。 Since your a getting an Application with getContext() , casting it to Activity causes the ClassCastExecption . 由于您使用getContext()获取应用程序,将其强制转换为Activity会导致ClassCastExecption

replace your line with this : 用这个替换你的行:

if you are using this code inside activity then use this: 如果您在活动中使用此代码,请使用此:

Display display = this.getContext().getWindowManager().getDefaultDisplay();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM