Android 桌面小组件 AppWidgetProvider(2)
1.生命周期
2.怎么处理点击事件
3.怎么创建集合
4.怎么处理动画效果
1.生命周期
1.1 添加小组件的生命周期
onEnabled:
onReceive:
onUpdate:
onReceive:
onAppWidgetOptionsChanged:
onReceive:
1.2 移除小组件的生命周期
onDeleted:
onReceive:
onDisabled:
onReceive:
2.怎么处理点击事件
这个问题解决方案的关键是 设置广播action
<receiver android:name=".listWidget.ListWidget">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
<action android:name="com.zg.todesk.CLICK" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/listwidget" />
</receiver>
这里添加的是
<action android:name="com.zg.todesk.CLICK" />
然后再组件中,发送广播,就能在onReceive中收到消息,然后做相应的处理就好
val pendingIntent = PendingIntent.getBroadcast(
context,
0,
Intent(context, MuyuAppWidget::class.java).apply {
action = "com.zg.todesk.CLICK"
},
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
views.setOnClickPendingIntent(R.id.rl_muyu, pendingIntent)//这里选择最大的控件
然后onReceive处理消息
override fun onReceive(context: Context?, intent: Intent?) {
super.onReceive(context, intent)
Log.e("zxd", "onReceive: ${intent!!.action}")
if (intent!!.action == "com.zg.zanglidemo.ANIM") {
...
}
}
3.怎么创建集合
这里简单的举一个例子。
1.声明AppWidgetProviderInfo XML
<?xml version="1.0" encoding="UTF-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:initialLayout="@layout/list_widget_layout"
android:minWidth="280dp"
android:minHeight="280dp"
android:updatePeriodMillis="0">
<!-- sdk1.5之后updatePeriodMillis已失效,置为0,循环执行自行在代码中实现 -->
</appwidget-provider>
2.使用 AppWidgetProvider 类处理 widget 广播
<!-- list widget -->
<receiver android:name=".listWidget.ListWidget">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
<action android:name="com.zg.todesk.CLICK" />
</intent-filter>
<meta-data
android:name&#