我刚刚开始进行 Android 开发,我已经创建了一个不错的小部件,可以在我的主屏幕上显示一些信息.但是,我现在想在我的小部件上实现一个 Button,以更新我的小部件 TextView 中的信息.
I am just getting started with Android development and I have created a nice little widget that displays some info on my home screen. However, I now want to implement a Button on my widget that updates the info in my widget TextView.
任何人都可以建议如何去做吗?
Can anyone advise how to go about doing this?
谢谢
已解决 - 如果您想创建 Button 来更新 Android AppWidget,我可以确认不需要 Activity.
Solved - I can confirm that an Activity is NOT needed if you want create a Button to update an Android AppWidget.
我已经能够实现我的 AppWidgetProvider 类,以便它在 AndroidManifest.xml 中向广播接收器注册一个 android.appwidget.action.APPWIDGET_UPDATE 意图过滤器,然后触发 AppWidgetProvider 类中的 onUpdate 事件(在然后运行 UpdateService).
I have been able to implement my AppWidgetProvider class such that it registers an android.appwidget.action.APPWIDGET_UPDATE intent-filter with the Broadcast receiver in the AndroidManifest.xml, which then fires the onUpdate event in the AppWidgetProvider class (which in turn then runs the UpdateService).
<!-- Broadcast Receiver that will process AppWidget updates -->
<receiver android:name=".MyWidget" android:label="@string/widget_name">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data android:name="android.appwidget.provider" android:resource="@xml/widget" />
</receiver>
我的 AppWidgetProvider 类中的 UpdateService 然后使用 onHandleIntent 运行私有 buildUpdate 方法 - 该方法通过调用 setOnClickPendingIntent 来注册 onClick 事件,如下所示:
The UpdateService in my AppWidgetProvider class then uses onHandleIntent to run a private buildUpdate method - which registers the onClick event with a call to setOnClickPendingIntent as follows:
// set intent and register onclick
Intent i = new Intent(this, MyWidget.class);
PendingIntent pi = PendingIntent.getBroadcast(context,0, i,0);
updateViews.setOnClickPendingIntent(R.id.update_button,pi);
这里是一个工作示例的一些源代码的链接,它显示了如何使用更新按钮来更新 Twitter 小部件:
Here is a link to some source code of a working example, which shows how an update button can be used to update a Twitter widget:
https://github.com/commonsguy/cw-advandroid/树/b01438e7f0fed8f795ddec4be43066905f03d0cc/AppWidget/TwitterWidget
这篇关于如何在 Android Widget 上实现 Button的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!