更新应用程序中的ListView小部件

4

当我试图从我的应用程序更新内容时,我的应用小部件出现了问题。我的小部件包含一个列表视图。

列表视图运行良好,每30分钟更新一次,但是当我在应用程序中进行更改时,我还需要更新它。以下是我的代码:

public class WidgetListProvider extends AppWidgetProvider {

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        final int N = appWidgetIds.length;
        ComponentName component;
        for (int i = 0; i < N; ++i) {
            RemoteViews remoteViews = updateWidgetListView(context,
                    appWidgetIds[i]);
            appWidgetManager.updateAppWidget(appWidgetIds[i], remoteViews);

            component=new ComponentName(context,WidgetListProvider.class);
            appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.listViewWidget);
            appWidgetManager.updateAppWidget(component, remoteViews);
        }

        super.onUpdate(context, appWidgetManager, appWidgetIds);
    }

    private RemoteViews updateWidgetListView(Context context, int appWidgetId) {
        RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_list_layout);

        Intent svcIntent = new Intent(context, WidgetService.class);
        svcIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
        svcIntent.setData(Uri.parse(svcIntent.toUri(Intent.URI_INTENT_SCHEME)));
        remoteViews.setRemoteAdapter(R.id.listViewWidget, svcIntent);
        remoteViews.setEmptyView(R.id.listViewWidget, R.id.empty_view);
        return remoteViews;
    }

}

在列表更新后,您是否调用了notifyDataSetChanged()函数? - Tushar Gogna
2个回答

5

将此代码放入您更新内容的应用程序中。

AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
int appWidgetIds[] = appWidgetManager.getAppWidgetIds(new ComponentName(context, WidgetListProvider.class));
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.listViewWidget);

1

当我在应用程序中进行更改时,还需要更新它。

您可以通过静态的 getInstance() 方法在任何需要时获取 AppWidgetManager。只要您跟踪需要更新的应用程序小部件 ID,当其他工作需要更新应用程序小部件内容时,您可以在现有代码中大部分运行。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接