RemoteViewFactory onDataSetChanged()每个notifyAppWidgetViewDataChanged()只调用一次

时间:2017-09-25 08:20:42

标签: android listview widget android-widget

我正在构建一个小部件来加载每个食谱的成分列表。我的目标是能够拥有窗口小部件的多个实例,并独立地加载/更新其成分列表(ListView)。我已为用户设置配置活动以选择配方。配置并填充remoteViews并将RemoteAdapter作为我的成分列表后,该方法将始终调用:

appWidgetManager.updateAppWidget(mAppWidgetId, views);
appWidgetManager.notifyAppWidgetViewDataChanged(mAppWidgetId, R.id.widget_list_view_layout);

updateAppWidget可以很好地更新非集合视图,但是,我对于我的集合视图,即成分列表,我已经熟悉了notifyAppWidgetViewDataChanged()。

我第一次将小部件添加到屏幕(recipeId 4)时,它正确加载并调用正确的服务并查看工厂以填充远程listView。但是,如果我添加第二个,这是发生的事情(或缺乏):

D/WidgetUtils: createAppWidgetResult() with appWidgetId: 78, recipeId: 4
D/WidgetUtils: RecipeId of the ingredients passed: 4
D/WidgetRemoteViewService: onGetViewFactory() call received with mRecipeId 4
D/WidgetRemoteViewsFactory: WidgetRemoteViewsFactory() constructed with recipeId: 4
D/WidgetRemoteViewsFactory: onDataSetChanged() called
D/WidgetUtils: createAppWidgetResult() with appWidgetId: 79, recipeId: 1
D/WidgetUtils: RecipeId of the ingredients passed: 1 
D/WidgetUtils: createAppWidgetResult() with appWidgetId: 80, recipeId: 2
D/WidgetUtils: RecipeId of the ingredients passed: 2

日志结束

如果食谱ID 1

,我期待以下情况
D/WidgetRemoteViewService: onGetViewFactory() call received with mRecipeId **1**
D/WidgetRemoteViewsFactory: WidgetRemoteViewsFactory() constructed with recipeId: **1**
D/WidgetRemoteViewsFactory: onDataSetChanged() called

但正如您从上面的日志中可以看到的那样,1之后没有任何事情发生(与4是预期的行为不同)

UI明智地,任何随后创建的小部件列表视图实际上都具有配方4(而不是1)的成分,即使配置活动明确地将id传递为1 ... 2 ... 6 ...等。

奇怪的足够:只有在我从主屏幕中删除所有小部件,然后添加一个小部件,例如食谱ID 1,然后它的onDataSetChanged()将被调用?!,再次,任何后续的小部件都不会被调用。

查看屏幕截图 Nutella Pie Recipe的id为4,而Brownies Recipe的id为1.首先添加Nutella Pie小部件,Nutella的成分Pie正确加载。布朗尼是第二位,正如你所看到的,这些成分是从第一种成分转移而来的,它们是不正确的。

在模拟器和真实设备上测试> API 21,结果相同。

enter image description here

1 个答案:

答案 0 :(得分:2)

@Joe onGetViewFactory only called once for multiple widgets

在这里找到答案

事实证明,它是关于RemoteViewService意图处理的方式。我正在创建RemoteViewService意图,就像我99.999%通常在任何活动中所做的那样,例如:

// Create intent to start the service and to act as the remote listView adapter
Intent remoteViewIntent = new Intent(context, WidgetRemoteViewService.class);
remoteViewIntent.putExtra(EXTRA_RECIPE_ID, recipeId);
views.setRemoteAdapter(R.id.widget_recipe_ingredients_list, remoteViewIntent);

解决方案:而不是

 remoteViewIntent.putExtra(EXTRA_RECIPE_ID, recipeId);

将其更改为:

 remoteViewIntent.setData(Uri.fromParts("content", String.valueOf(recipeId), null));

并在RemoteViewsService的onGetViewFactory()中,从意图中获取数据,如下所示:

long mRecipeId = Long.valueOf(intent.getData().getSchemeSpecificPart());