我已经看到了有关如何更新小部件的几个问题,但没有任何问题可以解决我的问题。
我创建了一个具有textview的小部件,我希望在创建小部件时动态更新。 我有一个在屏幕上添加小部件时调用的配置活动。我将值存储在sharedpreferences中并将其检索到onUpdate。问题是小部件没有得到更新。知道如何做到这一点?单击窗口小部件后,我不想更新textview,只需在创建时显示正确的文本。
public class AndroidWidget extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
ComponentName thisWidget = new ComponentName(context,
AndroidWidget.class);
int[] allWidgetInstancesIds = appWidgetManager
.getAppWidgetIds(thisWidget);
for (int widgetId : allWidgetInstancesIds) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.widget_layout);
// Create an intent that when received will launch the PopUpActivity
Intent intent = new Intent(context, AndroidWidget.class);
intent.setAction(SHOW_POPUP_DIALOG_ACTION);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
widgetId, intent, 0);
// Set up the onClickListener of the widget
remoteViews.setOnClickPendingIntent(R.id.myText, pendingIntent);
SharedPreferences prefs = context.getSharedPreferences(
String.valueOf(widgetId), Context.MODE_PRIVATE);
remoteViews.setTextViewText(R.id.myText,
prefs.getString("storedtext", null));
appWidgetManager.updateAppWidget(widgetId, remoteViews);
}
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
这实际上只是在点击或创建另一个小部件后才更新textview。
答案 0 :(得分:3)
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
//set widget id
ComponentName thisWidget = new ComponentName(context, WidgetProvider.class);
int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
for (int i = 0; i < appWidgetIds.length; i++) {
Intent intentService = new Intent(context, WidgetService.class);
intentService.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
intentService.setData(Uri.parse(intentService.toUri(Intent.URI_INTENT_SCHEME)));
RemoteViews widget = new RemoteViews(context.getPackageName(), R.layout.widget);
Intent clickIntent = new Intent(context, MainActivity.class);
PendingIntent clickPI = PendingIntent.getActivity(context, 0, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
widget.setTextViewText(R.id.currency, " Dollar");
appWidgetManager.updateAppWidget(appWidgetIds[i], widget);
}
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
此代码适用于我。你可以试试这个。