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

标签 android listview widget android-widget

当我尝试从我的应用程序更新内容时,我的 App Widget 出现问题。我的小部件包含一个 ListView 。

ListView 工作正常,每 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;
    }

}

最佳答案

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

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

关于android - 使用应用程序更新 ListView 小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28941472/

相关文章:

java - ListView 内存使用

qt - Gtk-关键 ** : IA__gtk_widget_style_get: assertion `GTK_IS_WIDGET (widget)' failed

qt - 使用 Qt 时将键盘输入定向到小部件

android - Layout_below 在我的 ListView 中不起作用

android - 如何提供2个Retrofit接口(interface)宽度不同级别的日志记录?

android - 如何在 XML 中为 Android Google MapFragment 设置精简模式?

android - System.currentTimeMillis() 是两个设备之间相差几个小时的值

c# - 由于其保护级别而无法访问

flutter - flutter :从小部件中获取小部件的屏幕截图

android - 请求 logcat 错误索引 -1,大小为 24