I tried to create a widget and I succeeded, but how can I meet the click needs of the tools in the widget?
What I'm talking about is not redirecting onto an activity, I'm looking for a method where I can create a function.
The layout file used for the widget below
<RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:id="@+id/kare"
android:theme = "@style/Theme.Mytwo.AppWidgetContainer" >
<Button
android:id = "@+id/appwidget_text"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_centerInParent = "true"
android:background = "#048018"
android:text = "clean"
android:textSize = "24sp"
android:padding="15dp"
android:textStyle = "bold" />
</RelativeLayout >
This is my widget provider class
class NewAppWidget : AppWidgetProvider() {
override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) { // There may be multiple widgets active, so update all of them
for (appWidgetId in appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId)
}
}
}
internal fun updateAppWidget(context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int) {
val views = RemoteViews(context.packageName, R.layout.new_app_widget )
appWidgetManager.updateAppWidget(appWidgetId, views)
}
And finally my provider info file
<appwidget-provider xmlns:android = "http://schemas.android.com/apk/res/android"
android:description = "@string/app_widget_description"
android:initialKeyguardLayout = "@layout/new_app_widget"
android:initialLayout = "@layout/new_app_widget"
android:minWidth = "100dp"
android:minHeight = "40dp"
android:previewImage = "@drawable/ic_launcher_foreground"
android:previewLayout = "@layout/new_app_widget"
android:resizeMode = "horizontal|vertical"
android:targetCellWidth = "2"
android:targetCellHeight = "2"
android:updatePeriodMillis = "86400000"
android:widgetCategory = "home_screen" />
I'm not sure what you mean by "create a function". The only way to get something to happen when a widget is clicked is via
RemoteViews#setOnCheckedChangeResponseorRemoteViews#setOnClickFillInIntentorRemoteViews#setOnClickPendingIntentorRemoteViews#setOnClickResponse. Apart from callingRemoteViews.RemoteResponse#addSharedElement, all that any of these can do is to send out anIntent, which can start anActivityor awaken aBroadcastReceiver.You can't execute your own code inside the widget: any code that you want to execute in response to a click on a widget has to be in the
Activityor theBroadcastReceiver. It doesn't have to be anActivityor aBroadcastReceiverinside the app that created the widget, although it usually will be.Since the
RemoteViewsis created inside your app'sAppWidgetProvider#updateAppWidget, you can put theappWidgetIdas an extra into thePendingIntent, so you can tell which widget was clicked.