How to implement a Button on an Android Widget

前端 未结 2 1946
别那么骄傲
别那么骄傲 2020-12-08 15:26

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 But

2条回答
  •  攒了一身酷
    2020-12-08 16:03

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

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

    
    
       
          
       
       
    
    

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

    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

提交回复
热议问题