AppWidget Screen Orientation

2019-08-23 22:00发布

Here is my question. I have an appwidget which works perfectly in a portrait screen orientation. However, When i changed my screen orientation to landscape my appWidget's width and height changing automatically by the home screen launcher and the problem is in landscape mode my widget's height is not set properly by the homescreen launcher. So, I need to detect is screen orientation changed and re-size my appwidget. I've googled it but still i don't have any idea how can i do that. If it was an activity it was simple but it's not. I'll be gratefull if anyone has idea about this.

2条回答
看我几分像从前
2楼-- · 2019-08-23 22:18
  1. Define bools.xml in both values-port and values-land

    In values-port/bools.xml

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <bool name="portrait">true</bool>
    </resources>
    

    In values-land/bools.xml

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <bool name="portrait">false</bool>
    </resources>
    
  2. Get boolean by Context.getResources() in code

    private static boolean isPortrait(Context context) {
        return context.getResources().getBoolean(R.bool.portrait);
    }
    
查看更多
我命由我不由天
3楼-- · 2019-08-23 22:23

When the screen orientation changes your AppWidgetProvider onUpdate method gets called. You can use the following function to get if you are in portrait or landscape mode and then update your remote views based on that.

private static boolean isPortrait (Context cx) {
Display d = ((WindowManager) cx.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();

if (d.getWidth() == d.getHeight()) {
    return false;
} else if (d.getWidth() < d.getHeight()) {
    return true;    
} else {
    return false;
}
}

Hope this helps.

查看更多
登录 后发表回答