在 ViewFlipper 小部件中的各个元素上设置点击监听器

Setting click listeners on individual elements in a ViewFlipper widget

我正在构建一个由 ViewFlipper 和 运行 支持的集合小部件,但在遵循 adding behavior to individual items 上的 Android 文档时遇到了麻烦。

我想创建两个箭头,将 ViewFlipper 移动到其上一个和下一个视图,如此模型所示:

在我的 WidgetServicegetViewAt() 方法中,我使用以下代码创建填充意图:

final Intent fillInIntent = new Intent();
final Bundle bundle = new Bundle();
bundle.putInt(WidgetProvider.EXTRA_ID, mWidgetItems.get(position));
fillInIntent.putExtras(bundle);
remoteViews.setOnClickFillInIntent(R.id.btn_widget_next, fillInIntent);
remoteViews.setOnClickFillInIntent(R.id.btn_widget_previous, fillInIntent);

然后在我的 WidgetProvider 我有这个:

// Adding collection list item handler
final Intent onItemClick = new Intent(context, WidgetProvider.class);
onItemClick.setAction(NAVIGATE);
onItemClick.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, id)
onItemClick.setData(Uri.parse(onItemClick.toUri(Intent.URI_INTENT_SCHEME)));
final PendingIntent onClickPendingIntent = PendingIntent
  .getBroadcast(context, id, onItemClick,
     PendingIntent.FLAG_UPDATE_CURRENT);
rv.setPendingIntentTemplate(R.id.widget_view_flipper, onClickPendingIntent);

这里的设计让我感到困惑的是我是否应该在每个按钮上调用 setOnClickFillInIntent。如果我确实在每个按钮上设置了意图,我需要一种方法来确定在我的 WidgetProvideronUpdate 方法中单击了哪个按钮(我现在所拥有的只是视图在 ViewFlipper).不幸的是,我找不到使用点击侦听器进行多个操作的 Widget 示例。

您链接到 的文档 以下句子有点误导人:

Your RemoteViewsFactory must set a fill-in intent on each item in the collection.This makes it possible to distinguish the individual on-click action of a given item

好吧,除非您尝试,否则您永远不会真正知道:毕竟可以为 RemoteViews 项目的个别子项 设置填充意图 。但是您必须为每个按钮使用单独的 Intent。我将展示如何使用 NEXT 按钮:

final Intent fillInIntent = new Intent();
final Bundle bundle = new Bundle();
bundle.putInt(WidgetProvider.EXTRA_ID, mWidgetItems.get(position));
bundle.putBoolean("FLIP_TO_NEXT", true);
fillInIntent.putExtras(bundle);
remoteViews.setOnClickFillInIntent(R.id.btn_widget_next, fillInIntent);

然后您必须检查 Intent 操作(导航)以及 onReceive()intent.getBooleanExtra("FLIP_TO_NEXT", false) 的值并相应地更新应用程序小部件。例如,如果 "NEXT" 被点击:

ComponentName me = new ComponentName(this, ViewFlipperWidget.class);
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this); 
int appWidgetID = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
if (appWidgetID != AppWidgetManager.INVALID_APPWIDGET_ID)
{
     RemoteViews rv = new RemoteViews(getPackageName(), R.layout.view_flipper_widget);
     if (intent.getBooleanExtra("FLIP_TO_NEXT", false))
     {
          rv.showNext(R.id.viewFlipper);
     }
     else 
     {
          rv.showPrevious(R.id.viewFlipper);
     }
     appWidgetManager.updateAppWidget(appWidgetID, rv);
}