【发布时间】:2019-08-28 19:46:20
【问题描述】:
ListView 的 android 小部件中未触发 Click 事件
我在小部件的列表视图的每一行中都有按钮,我想让它们可点击。我正在使用 setPendingIntentTemplate 和 setOnClickFillInIntent 并且希望触发 onReceive 方法?
RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.my_app_widget);
Intent intent = new Intent(context, MyWidgetRemoteViewsService.class);
rv.setRemoteAdapter(R.id.drinks_list, intent);
PendingIntent pendingIntent = PendingIntent.getActivity(context, appWidgetId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
rv.setPendingIntentTemplate(R.id.drinks_list, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, rv);
MyAppWidgetRemoteViewsFactory.java
public RemoteViews getViewAt(int position) {
RemoteViews drinks_view = new RemoteViews(mContext.getPackageName(), R.layout.drink_row);
drinks_view.setTextViewText(R.id.drink_name, drinkItems.get(position).text);
Bundle extras = new Bundle();
extras.putInt(MyAppWidget.DRINK_UPDATE, position);
Intent fillInIntent = new Intent();
fillInIntent.putExtras(extras);
drinks_view.setOnClickFillInIntent(R.id.minusButton, fillInIntent);
return drinks_view;
}
drink_row.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:background="@drawable/whiteroundcorner"
android:layout_height="wrap_content">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/minusButton"
android:backgroundTint="#27A9FF"
android:text="-"
android:clickable="true"
android:minWidth="60dp"
android:textColor="#FFFFFF"
android:layout_alignParentLeft="true">
</RelativeLayout>
public class MyWidgetRemoteViewsService extends RemoteViewsService {
@Override
public RemoteViewsFactory onGetViewFactory(Intent intent) {
return new MyAppWidgetRemoteViewsFactory(this.getApplicationContext(),intent);
}
}
<receiver android:name=".MyAppWidget">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<intent-filter>
<action android:name="com.developer.drinklogger.EXTRA_ITEM" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/my_app_widget_info" />
</receiver>
<service android:name=".MyWidgetRemoteViewsService"
android:permission="android.permission.BIND_REMOTEVIEWS"></service>
【问题讨论】:
-
对不起,忽略我之前的评论。您的
Intent的目标是MyWidgetRemoteViewsService。您提到了onReceive()方法。您的PendingIntent是通过getActivity()获得的。你想触发哪个,那里?Service、BroadcastReceiver或Activity? -
感谢您的回复。我添加了 MyWidgetRemoteViewsService 代码。 onReceive 是 AppWidgetProvider 的一部分
-
好的,那个类实际上是你的
RemoteViewsService,你真的不希望点击开始那个,所以我们需要改变Intent所针对的类。你提到onReceive()。您是否试图让点击触发您的AppWidgetProvider? -
啊,好的,刚刚看到您的编辑。将
Intent构造函数中的.class更改为您的AppWidgetProvider子类,然后将PendingIntent调用更改为getBroadcast(),而不是getActivity()。 -
再次感谢!当我现在进入主屏幕时它崩溃了“启动器不断停止”。我已经添加了我的清单。