【问题标题】:Providing click method to widgets为小部件提供点击方法
【发布时间】:2021-11-05 05:47:33
【问题描述】:

我尝试创建一个小部件,我成功了,但是如何满足小部件中工具的点击需求?

我所说的不是重定向到一个活动,我正在寻找一种可以创建函数的方法。

下方小部件使用的布局文件

<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 >

这是我的小部件提供程序类

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)
}

最后是我的提供商信息文件

<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" />

【问题讨论】:

    标签: android-studio kotlin widget click appwidgetprovider


    【解决方案1】:

    我不确定您所说的“创建函数”是什么意思。单击小部件时发生某些事情的唯一方法是通过RemoteViews#setOnCheckedChangeResponseRemoteViews#setOnClickFillInIntentRemoteViews#setOnClickPendingIntentRemoteViews#setOnClickResponse。 除了拨打RemoteViews.RemoteResponse#addSharedElement, 所有这些都可以做的就是发送一个Intent,它可以启动一个Activity或唤醒一个BroadcastReceiver

    您无法在小部件内执行您自己的代码:任何您想要响应点击小部件而执行的代码都必须位于ActivityBroadcastReceiver 中。它不必是创建小部件的应用程序中的ActivityBroadcastReceiver,尽管通常是这样。

    由于RemoteViews 是在您的应用程序的AppWidgetProvider#updateAppWidget 中创建的,您可以将appWidgetId 作为额外内容添加到PendingIntent 中,这样您就可以知道点击了哪个小部件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-09
      • 1970-01-01
      • 2022-08-04
      • 1970-01-01
      • 2020-09-02
      • 2014-05-23
      相关资源
      最近更新 更多