方向改变后,小部件上的按钮无响应。

12

可能是重复问题:
更改方向后,小部件上的按钮无响应

我遇到了一个问题,我的appwidget中有一个ImageView,我在xml布局中注册了一个pendingintent,该pendingintent在OnReceive方法中处理。 一切都正常工作,直到我改变手机方向。此时,小部件不再起作用,我点击图像,但什么也不会发生。 这个问题与这个问题完全相同: 更改方向后,小部件上的按钮无响应 问题出在哪里,如何解决? 谢谢。


你好,我回答了你在发布的链接中提出的问题。当你旋转屏幕时,会导致小部件被重新创建。当小部件被重新创建时,你需要重新绑定点击处理程序 - 即再次附加挂起的点击事件。这就是为什么该服务对于此场景很有效。它捕获 onConfigurationChanged 事件并将处理程序重新绑定到 UI 组件上。 - jagsaund
1
谢谢,没有使用服务的帮助,只是在OnReceive方法中重新设置了setOnClickPendingIntent。 - Alex
1
你能告诉我们如何使onReceive()在方向改变时被调用吗?我遇到了同样的问题,但我的AppWidgetProvider.onReceive()没有为此事件被调用。 - Martin Stone
没关系:问题已解决(详见下文)。 - Martin Stone
4个回答

9
我最终成功地重新创建了原帖中的无服务解决方案。这里是记录的秘密:每当您更新远程视图时,必须更新所有您曾经更新过的内容。我的应用程序正在更新一些可视元素,但未再次设置按钮处理程序。这导致处理程序停止工作 - 不是立即停止 - 只有在旋转更改后才会停止,因此引起了混淆。
如果操作正确,您无需拦截配置更改广播,旋转后将再次使用上次设置的远程视图。您的AppWidgetProvider不需要进行任何调用。

2

我遇到了类似的问题,但是按照Alex建议的解决方案,我的应用现在运行良好。

"......在OnReceive方法中重新设置setOnClickPendingIntent,就可以不借助服务而解决问题"

我追踪了onReceive方法,发现每次我改变设备的方向时都会调用它,因此我在onReceive方法中再次调用了小部件的配置。

总之,我不确定这是否是解决该问题的最佳方法,如果有人知道更好的解决方案,请分享。

谢谢。


1

每当您更新小部件的外观时(使用Activity或Broadcast Receiver [App widget provider]),您还必须重新分配所有单击处理程序的PendingIntents,然后像往常一样调用updateAppWidget()

使用setTextViewText()的示例:

// This will update the Widget, but cause it to
// stop working after an orientation change.
updateWidget()
{
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
remoteViews.setTextViewText(R.id.widget_text_view, "Updated widget");

appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
}


// This is the correct way to update the Widget,
// so that it works after orientation change.
updateWidget()
{
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
remoteViews.setTextViewText(R.id.widget_text_view, "Updated widget");

Intent intent = new Intent(context, MyWidgetActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, ...);
remoteViews.setOnClickPendingIntent(R.id.widget_click_button, pendingIntent);

appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
}


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