我阅读了 hellowidget 教程和开发指南的 App Widgets.然后我知道如何创建一个包含按钮或文本或其他内容的小部件.
I read the hellowidget tutorial and Dev Guide' App Widgets. Then I know how to create a widget which contains button or text or something.
但我真正想做的是让它与我的应用交互.例如,我想创建一个具有文本视图的小部件,当我单击它时,它会向我的活动发送一个 PendingIntent,我可以在其中编辑文本.
But what I really want to do is making it interact with my app. For example, I want to create a widget that has a text view, and when I click it, it sends a PendingIntent to my activity in which I can edit the text.
我可以执行发送 PendingIntent"步骤.但是我在活动中编辑文本后,小部件如何读取它?
I can do the step "sends a PendingIntent". But after I edit text in acitivy, how does the widget read it?
推荐答案你需要做的是注册一个自定义的intent,例如在你的AppWidgetProvider中注册一个ACTION_TEXT_CHANGED,例如:
What you need to do is register a custom intent, for example ACTION_TEXT_CHANGED in your AppWidgetProvider like this for example:
public static final String ACTION_TEXT_CHANGED = "yourpackage.TEXT_CHANGED";在此之后,您需要在您的 AndroidManifest.xml 中注册您希望在接收者标签的意图过滤器部分接收此意图,如下所示:
After this, you need to register in your AndroidManifest.xml that you want to receive this intents in the intent-filter section of your receiver tag like this:
<receiver android:name=".DrinkWaterAppWidgetProvider"> <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> <action android:name="yourpackage.TEXT_CHANGED" /> </intent-filter> <meta-data android:name="android.appwidget.provider" android:resource="@xml/appwidget_info" /> </receiver>然后你必须在你的 AppWidgetProvider 中扩展 onReceive 方法,并确保你处理你的意图是这样的:
Then you have to extend the onReceive method in your AppWidgetProvider and make sure that you're handling your intent like this:
@Override public void onReceive(Context context, Intent intent) { super.onReceive(context, intent); if (intent.getAction().equals(ACTION_TEXT_CHANGED)) { // handle intent here String s = intent.getStringExtra("NewString"); } }以上所有设置完成后,您只需要在文本更改后在活动中广播意图,如下所示:
After all the above is set up, you just need to broadcast the intent in your activity after the text has changed like this:
Intent intent = new Intent(YourAppWidgetProvider.ACTION_TEXT_CHANGED); intent.putExtra("NewString", textView.getText().toString()); getApplicationContext().sendBroadcast(intent);其中NewString"应更改为您为字符串提供的名称.
Where "NewString" should be changed to the name you to give the the string.
希望对你有帮助.
更多推荐
如何在活动和小部件之间共享数据?
发布评论