I’m working on a Todo List widget for my Android app. Each todo item features a “done” icon; when the user clicks it, I want to trigger an intent to a receiver that updates the database. I’ve created a ListView populated from my todo database, but I can’t make the items clickable using any available options for RemoteViews. Here’s my code:
internal fun updateTodoWidget(
context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int
) {
val views = RemoteViews(context.packageName, R.layout.todo_widget)
views.setRemoteAdapter(
R.id.list, Intent(context, WidgetService::class.java).apply {
putExtra("appWidgetId", appWidgetId)
}
)
views.setTextViewText(
R.id.count, (context.readSharedPreference("todoCount", 0) as Int).toString()
)
appWidgetManager.updateAppWidget(appWidgetId, views)
}
class WidgetService : RemoteViewsService() {
override fun onGetViewFactory(intent: Intent?): RemoteViewsFactory {
return DataProvider(this, intent)
}
}
class DataProvider(widgetService: WidgetService, val intent: Intent?) : RemoteViewsService.RemoteViewsFactory {
private var myListView: MutableList<Todo> = ArrayList()
private var mContext: Context? = null
override fun getViewAt(position: Int): RemoteViews {
val view = RemoteViews(mContext!!.packageName, R.layout.todo_item_widget)
view.setTextViewText(R.id.item_text, myListView[position].name)
view.setOnClickFillInIntent(
R.id.done, Intent(mContext, ActionReceiver::class.java).apply {
action = "doneTodo"
putExtra("id", myListView[position].id)
putExtra("appWidgetId", intent?.getIntExtra("appWidgetId", 69) ?: 69)
}
)
return view
}
}
Here’s the layout for the todo item:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:id="@+id/item"
android:layout_marginVertical="2dp"
android:gravity="center_vertical"
android:layout_height="match_parent">
<ImageView
android:layout_width="27dp"
android:src="@drawable/circle"
android:id="@+id/done"
android:layout_marginEnd="5dp"
android:layout_height="27dp"/>
<TextView
android:id="@+id/item_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/colorOnSurface"
android:textSize="17sp"
tools:text="Random task" />
</LinearLayout>
The receiver class is functioning correctly for other tasks, but it does not receive any intents when clicking the item.
I experimented with various intents, such as Activity intents, but it seems the ListView items aren’t clickable.