一直在尝试不同的方法来为我的小部件中的 ListView 实现 onClick 事件,但无济于事。
我的小部件在 AndroidManifest.xml 中定义:
<!-- Widget -->
<receiver android:name=".widget.AppWidgetProvider">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
</intent-filter>
<meta-data android:name="android.appwidget.provider" android:resource="@xml/app_widget_info"/>
</receiver>
<service android:exported="false" android:name=".widget.AppWidgetService" android:permission="android.permission.BIND_REMOTEVIEWS"/>
我的第一种方法是使用 onReceive 接收意图并启动不同的活动:
// setPendingIntentTemplate in AppWidgetProvider
final Intent onClickIntent = new Intent(context, AppWidgetProvider.class);
onClickIntent.setAction(AppWidgetProvider.CLICK_ACTION);
onClickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
onClickIntent.setData(Uri.parse(onClickIntent.toUri(Intent.URI_INTENT_SCHEME)));
final PendingIntent onClickPendingIntent = PendingIntent.getBroadcast(context, 0,
onClickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
rv.setPendingIntentTemplate(R.id.widget_schedule_list, onClickPendingIntent);
// and setOnClickFillInIntent in the getViewAt() in RemoteViewsService.RemoteViewsFactory class
final Bundle extras = new Bundle();
final Intent fillInIntent = new Intent();
extras.putInt(TVTracWidgetProvider.EXTRA_ITEM, position);
fillInIntent.putExtras(extras);
rv.setOnClickFillInIntent(R.id.episode_schedule_widget_row, fillInIntent);
我的第二种方法是直接开始活动:
// setPendingIntentTemplate in AppWidgetProvider
TaskStackBuilder builder = TaskStackBuilder.create(context)
.addNextIntent(new Intent(context, MainActivity_.class));
builder.addNextIntent(new Intent(context, EpisodeActivity_.class));
rv.setPendingIntentTemplate(R.id.widget_schedule_list, builder.getPendingIntent(1, PendingIntent.FLAG_UPDATE_CURRENT));
// and setOnClickFillInIntent in RemoteViewsFactory getViewAt()
Bundle extras = new Bundle();
extras.putInt(EpisodeActivity.showIdExtra, episode.getShow().getId());
extras.putInt(EpisodeActivity.seasonNrExtra, episode.getSeasonNr());
extras.putInt(EpisodeActivity.episodeNrExtra, episode.getEpisodeNr());
Intent fillInIntent = new Intent();
fillInIntent.putExtras(extras);
rv.setOnClickFillInIntent(R.id.episode_schedule_widget_row, fillInIntent);
然而,这两种方法似乎都不起作用。pendingIntentTemplate 位于 ListView 的 id 上,onClickFillInIntent 位于每个行项的父布局上。谁能解释一下是什么导致点击不被触发?提前致谢!