How to set onclick listener to Button in Widgets in Android Studio Using kotlin

Viewed 724

Hello I am making a widget just to do something else but before that, I am unable to set on click listener to a text view in android studio kotlin

I have this todo_widget.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:theme="@style/ThemeOverlay.TodoWidgetMultipplatform.AppWidgetContainer">

      <TextView
          android:id="@+id/title"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="To Do List "
          android:layout_gravity="center"
          android:layout_marginTop="50dp"
          />
</LinearLayout>

and this is todowidget.kt

package com.example.todowidgetmultipplatform

import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.Context
import android.content.Intent
import android.util.Log
import android.widget.RemoteViews

/**
 * Implementation of App Widget functionality.
 */
class todoWidget : AppWidgetProvider()  {
    override fun onUpdate(
            context: Context,
            appWidgetManager: AppWidgetManager,
            appWidgetIds: IntArray
    ) {


        appWidgetIds.forEach { appWidgetId ->
            val pendingIntent: PendingIntent = Intent(context, MainActivity::class.java)
                    .let { intent -> PendingIntent.getActivity(context, 0, intent, 0) }


            val views: RemoteViews = RemoteViews(context.packageName, R.layout.todo_widget).apply {
                setOnClickPendingIntent(R.id.title,pendingIntent)
            }

            appWidgetManager.updateAppWidget(appWidgetId, views)
        }
    }
}

internal fun updateAppWidget(
        context: Context,
        appWidgetManager: AppWidgetManager,
        appWidgetId: Int
) {
    val widgetText = context.getString(R.string.appwidget_text)
    // Construct the RemoteViews object
    val views = RemoteViews(context.packageName, R.layout.todo_widget)

    // Instruct the widget manager to update the widget
    appWidgetManager.updateAppWidget(appWidgetId, views)
}

Now I want to set a listener to the textview so i can do something...

0 Answers
Related