我实现了一个widget
与ImageButton
和TextView
。 这ImageButton
发起activity
的点击时。 此activity
更新什么用户在活动写入插件文本EditText
。 现在的问题是,我只知道如何获得这样的标识:
for (int widgetId : allWidgetIds) {
// Create some random data
int number = (new Random().nextInt(100));
RemoteViews remoteViews = new RemoteViews(getApplicationContext()
.getPackageName(), R.layout.widget_layout);
Log.w("WidgetExample", String.valueOf(number));
//Here I should set text from edit text, but I'm using a random for testing.
remoteViews.setTextViewText(R.id.textView1,
"Random: " + String.valueOf(number));
appWidgetManager.updateAppWidget(widgetId, remoteViews);
}
此代码将明显改变所有的ID的数据,因为它里面for
。 反正是有,我可以过去和我的意图的点击为widgetid,这样我就可以消除for
? 这是我的widgetProvider:
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
// Get all ids
ComponentName thisWidget = new ComponentName(context, Widget.class);
allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
for (int widgetId : allWidgetIds) {
Intent i = new Intent(context, WidgetSetup.class);
i.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds);
i.setFlags(i.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
// Create some random data
int number = (new Random().nextInt(100));
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.widget_layout);
// Set the text
remoteViews.setTextViewText(R.id.textView1, String.valueOf(number));
Intent active = new Intent(context, Widget.class);
active.setAction(ACTION_WIDGET_REFRESH);
PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0);
remoteViews.setOnClickPendingIntent(R.id.imageButton1, actionPendingIntent);
active = new Intent(context, Widget.class);
active.setAction(ACTION_WIDGET_SETTINGS);
actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0);
remoteViews.setOnClickPendingIntent(R.id.imageButton2, actionPendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
}
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_WIDGET_REFRESH)) {
//Log.i("onReceive", ACTION_WIDGET_REFRESH);
Intent i = new Intent(context, MainActivity.class);
i.setFlags(i.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
} else if (intent.getAction().equals(ACTION_WIDGET_SETTINGS)) {
//Log.i("onReceive", AppWidgetManager.EXTRA_APPWIDGET_ID);
Intent i = new Intent(context, WidgetSetup.class);
i.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds);
//Here I tried to pass the widgetID with no luck.
//i.putExtra(pass widget id?);
i.setFlags(i.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
} else {
super.onReceive(context, intent);
}
}
谢谢