https://developer.android.com/guide/topics/appwidgets/index.html#Configuring
我阅读本教程和其他教程,使用户配置制作Widget。
我了解ConfigurationActivity会初始化窗口小部件,但窗口小部件将使用提供程序类中的“onUpdate”方法进行更新。
然后我的问题是,当调用onUpdate时,如何让小部件保留初始化数据?
例如,这就是我在configurationActivity中所拥有的,它从用户获取String输入并在textView中设置
public void onClick(View v) {
Context context = getApplicationContext();
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.widget_haruhi);
//Get String input.
String test = String.valueOf(name.getText());
remoteViews.setTextViewText(R.id.sinceWhen, test);
//But after 30 min it calls default update??
appWidgetManager.updateAppWidget(mAppWidgetId, remoteViews);
Intent resultValue = new Intent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
setResult(RESULT_OK, resultValue);
finish();
}
这就是我在Widget提供程序中所拥有的
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
final int count = appWidgetIds.length;
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_haruhi);
long days=getDays(2011,5,15);
//This field needs to be updated periodically
remoteViews.setTextViewText(R.id.daysText, days+context.getString(R.string.days));
// But this field needs to stay the same as initialised configuration
remoteViews.setTextViewText(R.id.daysText, ????);
Intent intent = new Intent(context, HaruhiWidgetProvider.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
for (int i = 0; i < count; i++) {
int widgetId = appWidgetIds[i];
appWidgetManager.updateAppWidget(widgetId, remoteViews);
}
}
小部件中的一个字段需要定期更新 但另一个需要将String显示为用户输入。 但是,在调用onUpdate时,此窗口小部件将被重置,初始化值将丢失。
如何解决此问题?我应该在SharedPreference中保存所有初始化数据并在每次收到更新信号时加载所有数据吗?