设备重启后如何获取小部件大小(适用于Android 4.4.4)

时间:2014-09-16 05:55:54

标签: android android-widget

我有一个小部件,其布局应根据当前小部件大小而改变。我使用以下代码来处理这样的要求。

public void onAppWidgetOptionsChanged(Context context,
                                      AppWidgetManager appWidgetManager,
                                      int appWidgetId,
                                      Bundle newOptions) {
    int heightInDp = newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT);
    int heightInCell = getCellSize(heightInDp);

    RemoteViews remoteViews = org.yccheok.jstock.gui.widget.Utils.getRemoteViews(appWidgetId, getWidgetWatchlistFragmentResourceId(context, appWidgetId));
    if (heightInCell >= 3) {
        remoteViews.setViewVisibility(R.id.header, View.VISIBLE);
    } else {
        remoteViews.setViewVisibility(R.id.header, View.GONE);
    }
    appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
}

这非常有效。直到我在Android 4.4.4中发现,当您关闭电源并打开设备电源时,只会触发onUpdate

但是,在4.1.2中,将触发onAppWidgetOptionsChanged。在这种情况下,根据窗口小部件大小来处理UI布局要容易得多。与onAppWidgetOptionsChanged一样,我们收到Bundle newOptions。从捆绑包中,我们可以查询当前的窗口小部件大小。

但是,我们如何在onUpdate中获取小部件大小?或者,换句话说,在设备重启后我们如何才能获得小部件大小?

1 个答案:

答案 0 :(得分:0)

这仅适用于具有Jelly Bean及以上的设备。

似乎有一个API可以达到这样的目的。

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
    Bundle bundle = appWidgetManager.getAppWidgetOptions(appWidgetId);
    heightInDp = bundle.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT);
}