我在我的小部件布局中添加了ImageButton
来触发小部件更新。我的布局是:
?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/widget"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#7F7F7F"
android:gravity="center"
android:orientation="horizontal"
android:padding="@dimen/marge_widget" >
<TextView
android:id="@+id/Text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="8"
android:textColor="#FF0000"
android:textSize="20sp" />
<ImageButton
android:id="@+id/UpdateButton"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_weight="1"
android:src="@android:drawable/stat_notify_sync" />
</LinearLayout>
在我的onUpdate
函数中,我将PendingIntent
附加到我的按钮上,如下所示:
intent = new Intent(contexte,myApp.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
pendingIntent = PendingIntent.getBroadcast(context,appWidgetId,intent,0);
vue.setOnClickPendingIntent(R.id.UpdateButton,pendingIntent);
问题是当我点击小部件的按钮时没有任何反应......
我的代码出了什么问题?
我可以补充一点,我的小部件在创建或调整大小时已正确更新。
答案 0 :(得分:0)
您需要在Intent extra中包含您的小部件ID。请注意,ACTION_APPWIDGET_UPDATE的doc指定了一个额外的ID列表。
查看AppWidgetProvider.onReceive的Android源代码,如果没有小部件ID,则不会调用onUpdate。因此,您需要将小部件ID添加为额外的意图。
不幸的是,下一个问题是当底层意图仅在附加内容中有所不同时,Android会重用PendingIntent实例。这意味着当用户创建新的窗口小部件实例(具有新ID)时,它所获取的PendingIntent仍将具有旧的窗口小部件ID。您可以通过在getBroadcast调用中使用PendingIntent.FLAG_UPDATE_CURRENT标志来解决该问题。
intent = new Intent(contexte, myApp.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { appWidgetId });
pendingIntent = PendingIntent.getBroadcast(context, appWidgetId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
vue.setOnClickPendingIntent(R.id.UpdateButton, pendingIntent);
现在,这将适用于已更新的LATEST窗口小部件实例。但是,如果用户添加了多个窗口小部件实例,则仍会出现问题。只有最新的按钮才有效。我过去通过将所有小部件ID存储在SharedPreferences中来解决了这个问题。然后,您可以检索ID列表并将其全部添加,而不仅仅是添加{appWidgetId}。我不会尝试在这里实现,但希望你能得到这个想法。