如何实现在Android窗口小部件一个按钮部件、如何实现、按钮、窗口

2023-09-12 07:22:51 作者:自我主宰

我刚刚接触Android的发展,我创建了一个可爱的小插件,显示我的主屏幕上的一些信息。不过,我现在想实现我的窗口小部件的按钮更新我的窗口小部件的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?

感谢

推荐答案

解决 - 我可以确认的是,如果你想创建一个按钮来更新Android的AppWidget的活动不需要

Solved - I can confirm that an Activity is NOT needed if you want create a Button to update an Android AppWidget.

我已经能够实现我这样的,它注册了一个android.appwidget.action.APPWIDGET_UPDATE意图过滤器与广播接收器在AndroidManifest.xml,然后触发了AppWidgetProvider类的OnUpdate事件(AppWidgetProvider类,在打开然后运行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方法 - 它注册的onClick事件调用setOnClickPendingIntent如下:

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

下面是一个链接到一个工作示例的一些源$ C ​​$ C,它显示了如何更新按钮可用于更新微博小工具:

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/tree/b01438e7f0fed8f795ddec4be43066905f03d0cc/AppWidget/TwitterWidget