如果您从 Provider 类更新,请从 onUpdate() 方法获取小部件 id,如下所示:
final int N = appWidgetIds.length;
for (int i=0; i<N; i++) {
int appWidgetId = appWidgetIds[i];
}
或者,如果您从 ConfigurationActivity 更新小部件,请从 onCreate 方法获取小部件 ID,如下所示:
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
}
从您的 widget_layout 中的按钮/图像视图使您的小部件启动 ConfigurationActivity
// Create intent pointing to ConfigurationActivity, in this example we are at ConfigurationActivity
Intent configurationIntent = new Intent(WidgetBarConfiguration.this, WidgetBarConfiguration.class);
// Create a extra giving the App Widget Id
configurationIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
// Create a pending intent giving configurationIntent as parameter
PendingIntent configurationPendingIntent = PendingIntent.getActivity(WidgetBarConfiguration.this, 0, configurationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
// Here we fecth the layout item and give it a action
RemoteViews views = new RemoteViews(WidgetBarConfiguration.this.getPackageName(), R.layout.widget_bar_layout);
// Setting onClick event that will lauch ConfigurationActivity
views.setOnClickPendingIntent(R.id.imageViewSettings, configurationPendingIntent);
// Updating widget
mWidgetManager.updateAppWidget(mAppWidgetId, views);
Intent resultValue = new Intent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
setResult(RESULT_OK, resultValue);
finish();
AndroidManifest.xml
<activity
android:name=".WidgetBarConfiguration"
android:label="@string/title_activity_widget_configuration"
android:launchMode="singleInstance"
android:theme="@style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
</intent-filter>
</activity>
看看这lauchMode = "singleInstance"
将确保单击时仅显示 ConfigurationActivity 布局,而没有附加任何其他活动布局。