【发布时间】:2014-07-13 22:06:41
【问题描述】:
在示例应用程序中,它执行 4 个动作,动作 1~4。我想让用户为每个不同的操作创建小部件按钮。当用户创建一个小部件时,配置活动允许用户选择一个操作。按下小部件应该执行操作。
问题在于,当为操作 1 创建一个小部件,然后为操作 2 创建另一个小部件时,操作 1 的小部件操作似乎被操作 2 的操作覆盖。也就是说,任何小部件都像最后一个小部件一样工作.我怎样才能解决这个问题?我已将完整项目上传至http://tempsend.com/E552810CFE(有效期至 2014 年 8 月 13 日)。
public class WidgetReceiver extends AppWidgetProvider
{
public WidgetReceiver()
{
}
private static final String WIDGET_BUTTON_CLICKED = "WidgetButtonClickedIntent";
@Override
public void onReceive(Context context, Intent intent)
{
super.onReceive(context, intent);
if (WIDGET_BUTTON_CLICKED.equals(intent.getAction()))
{
int actionID = intent.getIntExtra("ActionID", -1);
Toast.makeText(context, "Doing action " + actionID, Toast.LENGTH_SHORT).show();
Log.d("StackOverflow", "Doing action " + actionID);
}
}
@Override
public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager,
int appWidgetId, Bundle newOptions)
{
int actionID;
super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions);
Log.d("StackOverflow", "onAppWidgetOptionsChanged is called for " + appWidgetId);
Bundle bun = appWidgetManager.getAppWidgetOptions(appWidgetId);
actionID = bun.getInt("ActionID");
Log.d("StackOverflow", "The action ID is " + actionID);
RemoteViews remoteViews;
remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_button);
remoteViews.setTextViewText(R.id.textView, "Action " + actionID);
remoteViews.setOnClickPendingIntent(R.id.textView,
getPendingSelfIntent(context, WIDGET_BUTTON_CLICKED, actionID));
appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
{
super.onUpdate(context, appWidgetManager, appWidgetIds);
String ids = Arrays.toString(appWidgetIds);
Log.d("StackOverflow", "onUpdate is called for " + ids);
}
protected PendingIntent getPendingSelfIntent(Context context, String action, int actionID)
{
Intent intent = new Intent(context, getClass());
intent.setAction(action);
intent.putExtra("ActionID", actionID);
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
}
【问题讨论】: