我有一个主屏幕小部件,一个列表小部件,通常情况下,我希望每个项目在单击时打开活动。
我看到很多答案都是使用toast和广播,但我想要它打开一个活动。问题是,点击不起作用。
这是我所做的:
widget_info.xml
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minHeight="50dp"
android:minWidth="300dp"
android:previewImage="@mipmap/ic_launcher"
android:resizeMode="horizontal|vertical" />
< p>供应商< /p>
class StickyWidgetProvider : AppWidgetProvider() {
override fun onReceive(context: Context, intent: Intent) {
super.onReceive(context, intent)
if (ACTION_APPWIDGET_UPDATE == intent.action) {
updateWidget(context)
}
}
override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
for (i in 0 until appWidgetIds.size) {
val appWidgetId = appWidgetIds[i]
val rv = RemoteViews(context.packageName, R.layout.widget_container)
rv.setRemoteAdapter(R.id.widget_list, Intent(context, MyWidgetService::class.java))
val activityIntent = Intent(context, MainActivity::class.java)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
val pendingIntent = PendingIntent.getActivity(context, 0, activityIntent, PendingIntent.FLAG_UPDATE_CURRENT)
rv.setPendingIntentTemplate(R.id.widget_list, pendingIntent)
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetId, R.id.widget_list)
appWidgetManager.updateAppWidget(appWidgetId, rv)
}
}
private fun updateWidget(context: Context) {
val appWidgetManager = AppWidgetManager.getInstance(context)
appWidgetManager.notifyAppWidgetViewDataChanged(
appWidgetManager.getAppWidgetIds(
ComponentName(context, StickyWidgetProvider::class.java)
),
R.id.widget_list)
}
}
而 RemoteViewsFactory
class StickyWidgetRemoteViewsFactory(private val context: Context) : RemoteViewsService.RemoteViewsFactory {
private var itemList: List<MyItems>? = null
private fun updateWidgetListView() {
itemList = filled by somrthing
}
override fun onCreate() {
updateWidgetListView()
}
override fun onDataSetChanged() {
updateWidgetListView()
}
override fun onDestroy() {
itemList = null
}
override fun getCount(): Int {
return if (itemList != null)
itemList!!.size
else
0
}
override fun getViewAt(position: Int): RemoteViews {
val remoteView = RemoteViews(context.packageName, R.layout.widget_row)
val item = itemList!![position]
// fill the view //
val bundle = Bundle()
bundle.putParcelable(MainActivity.EXTRA_ITEM, item)
val fillInIntent = Intent().putExtras(bundle)
remoteView.setOnClickFillInIntent(R.id.widget_item, fillInIntent)
return remoteView
}
...
}
我就是在这里想不出哪里做错了。遵循https://developer.android.com/guide指南,我把
setPendingIntentTemplate
放在提供者(Provider)中,并在工厂中使用setOnClickFillInIntent
进行填充,但是项目点击没有任何反应。
需要注意的是,该小部件是一个LinearLayout
,其中包含一些TextViews
,这些视图的属性分别为:android:textIsSelectable="false"
,android:clickable="false"
和android:focusable="false"
。
请问我该如何操作?