我一直在嘗試做同樣的事情,我想我已經破解了它。我在PreferenceActivity中處理onBackPressed()事件,並使用sendBroadcast()從那裏執行小部件更新。
在PreferenceActivity:
@Override
public void onBackPressed() {
Intent intent=getIntent();
Bundle extras=intent.getExtras();
int widgetId=extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
// this is the intent broadcast/returned to the widget
Intent updateIntent = new Intent(this, WidgetProvider.class);
updateIntent.setAction("PreferencesUpdated");
updateIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId);
sendBroadcast(updateIntent);
}
在你WidgetProvider:
@Override
public void onReceive(Context context, Intent intent) {
if ("PreferencesUpdated".equals(action)) {
// update your widget here
// my widget supports multiple instances so I needed to uniquely identify them like this
RemoteViews remoteView = new RemoteViews(context.getPackageName(), R.layout.widget);
int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID);
updateWidgetView(context, remoteView, appWidgetId);
}
}
注意:在1.5 onBackPressed不支持這麼註釋掉@覆蓋了onBackPressed並添加該代碼
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
Log.d(LOG_TAG, "onKeyDown() "+ keyCode);
if (keyCode==KeyEvent.KEYCODE_BACK && Integer.parseInt(Build.VERSION.SDK)<5) {
onBackPressed();
}
}
我應該補充一點,我是Android開發的新手,所以我可能完全是這樣做的錯了。我只能說這對我很有用:)
讓我知道你是怎麼回事。
這可能也幫助你:http://stackoverflow.com/questions/2697233/how-to-add-a-button-to-preferencescreen – 2011-10-07 08:56:15