在onCreate
功能,你應該叫
/**
* In onCreate() we have to ensure that if the user presses BACK or cancelled the activity,
* then we should not add app widget.
*/
setResult(RESULT_CANCELED);
,以確保如果關閉配置活動部件將不會增加家庭。以下代碼顯示瞭如何配置一個小部件。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* In onCreate() we have to ensure that if the user presses BACK or cancelled the activity,
* then we should not add app widget.
*/
setResult(RESULT_CANCELED);
setContentView(R.layout.activity_widget_settings);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null){
appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
}
if (appWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID){
finish();
return;
}
appWidgetManager = AppWidgetManager.getInstance(this);
views = new RemoteViews(this.getPackageName(), R.layout.my_app_widget);
}
你的配置之後,不要忘記調用:
Intent widgetIntent = new Intent();
widgetIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
setResult(RESULT_OK,widgetIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);