How to detect if a widget is on/off screen?

狂风中的少年 提交于 2020-01-03 03:08:29

问题


I'm writing a customized view similar to Grid which will be used to hold a large amount of images. I'm using ImageButton to display the images, and I only want to load images onto the buttons once they are on the screen (and just display a static background image when they are not). The reason for it is that I'm fetching images from some back-end service and I only want to fetch them when the buttons are on the screen.

To do that, I'd like to know if the widget is on the screen. Is it possible to detect if a widget like button is on/off screen? If not, any suggestions on how to achieve what I'm trying to do?


回答1:


I don't think you can. The framework will just send you an onUpdate request when the widget is created, and then again according to your update policy.

I don't see why there would be a reason to change the image when the widget isn't being shown. You're not saving the OS any resources by doing so; it already knows not to draw your widget when it's off-screen.




回答2:


You can use the following from Android 2.1 an onwards to check if the screen is on.

PowerManager mPower = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
boolean screen_is_on = mPower.isScreenOn();


来源:https://stackoverflow.com/questions/3817480/how-to-detect-if-a-widget-is-on-off-screen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!