简体   繁体   English

使用应用程序更新ListView小部件

[英]Update ListView Widget with Application

I have a problem with my App Widget when i try to update the content from my application. 当我尝试更新应用程序中的内容时,我的App Widget出现问题。 My widget contains a listview. 我的小部件包含列表视图。

The listview works fine and it updates every 30 minutes, but I also need to update it when i make changes in the application. listview工作正常,每隔30分钟更新一次,但是当我在应用程序中进行更改时,我还需要更新它。 Here is my code: 这是我的代码:

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;
    }

}

put this code in your application where you are updating content. 将此代码放在您正在更新内容的应用程序中。

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

I also need to update it when i make changes in the application 当我在应用程序中进行更改时,我还需要更新它

You can get an AppWidgetManager whenever you need to, via the static getInstance() method. 您可以通过静态getInstance()方法随时获取AppWidgetManager So long as you keep track of which app widget ID you need to update, you can largely go through your existing code when other work in your app requires your app widget contents to update. 只要您跟踪需要更新的应用小部件ID,当应用中的其他工作需要更新应用小部件内容时,您可以在很大程度上浏览现有代码。

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

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