Reprint please indicate source: http://blog.csdn.net/sk719887916/article/details/47027263
Many development projects will have the widget function, do not underestimate it, he is also one of the seven Android components, to the widget unfamiliar friends can read my previous article < Android widget working principle of a detailed (a) > Today we will implement a sliding widet, familiar with the development of the next common widget.
Create a AppwidgetproviderThis class is the control core of the widget, the main control to add, delete, update and so on. He is a subclass of Brodcast and can have all the features of the broadcast. create Myapplistwidgetprovider class inheritance Appwidgetprovider, implement the method, OnUpdate (), OnReceive (), onenabled (context context), OnD Eleted (), ondisabled () The following three methods are optional and not selectable. 1 onUpdate () This method typically handles creating layouts and updating UI actions for widgets, and when the widget is added to the desktop it triggers the OnUpdate () method, where we can load a layout for the widget by getting remoteviews, and the remote view says, It is the Widget's resource management tool, which we can use to convert a widget to a support layout, support only a specific view, below I load a ListView for it, set a click event on the widget to use Pendingintent, With a deferred intent of new, and thenRemoteviews.setonclickpendingintent () to register a click event. The update layout can be obtained with Widgetmanager. Updateappwidget (Thiswidget, remoteviews) to load or update widget layouts, or through onreceive () receives a custom broadcast to call this method to update the layout.
@Override public void OnUpdate (context context, Appwidgetmanager Appwidgetmanager, int[] appwidgetids) { Gets the component name of the widget componentname thiswidget = new ComponentName (context, MYAPPLISTWIDGETPROVIDER.C LASS); Create a remoteview remoteviews remoteviews = new Remoteviews (Context.getpackagename (), R.layout.my_wi Dget_layout); Bind this widget to remoteviewsservice Intent Intent = new Intent (context, myremoteviewsservice.class); Intent.putextra (appwidgetmanager.extra_appwidget_id, appwidgetids[0]); Set Adapter Remoteviews.setremoteadapter (R.id.widget_list, intent); Set the View Remoteviews.setemptyview (R.id.widget_list, R.layout.none_data) displayed when the displayed widget_list is empty; Click List Trigger Event Intent clickintent = new Intent (context, myapplistwidgetprovider.class); Set action to make it easy to distinguish click event Clickintent.setaction (clickaction) in onreceive; Clickintent.setdata (Uri.parse (ClickintenT.touri (Intent.uri_intent_scheme)); Pendingintent pendingintenttemplate = pendingintent.getbroadcast (context, 0, clickintent, PENDINGINTENT.FL Ag_update_current); Remoteviews.setpendingintenttemplate (R.id.widget_list, pendingintenttemplate); Refresh Button Final Intent refreshintent = new Intent (context, myapplistwidgetprovider.class); Refreshintent.setaction ("Refresh"); Final Pendingintent refreshpendingintent = pendingintent.getbroadcast (context, 0, refreshintent, Pendingin Tent. Flag_update_current); Remoteviews.setonclickpendingintent (R.id.button_refresh, refreshpendingintent); Updated Wdiget appwidgetmanager.updateappwidget (Thiswidget, remoteviews); }
2 onreceive ()
The onreceive (), which is similar to broadcasting, uses hair to receive and process broadcasts, If we have registered Myapplistwidgetprovider as a appwidget in manifest.xml, then we do not have to add a action:<action android:name= "to this broadcast by adding a widget label." Android.appwidget.action.APPWIDGET_UPDATE "/>, the following <meta-data> tag is used to define the widget's properties, specify a widget description information, read the specific explanation A detailed article on the principle of the widget,
The <!--widget must be added to the manifest file, using the "receiver" label-- <receiver android:name= as Broadcaset receiver. Myapplistwidgetprovider "> <!--here to set Wdiget Update action-- <intent-filter> <action android: Name= "Android.appwidget.action.APPWIDGET_UPDATE"/> </intent-filter> <!--here to set up the widget description resource res /xml/my_widget.xml-- <meta-data android:name= "Android.appwidget.provider" Android:resource = "@xml/widget_info" > </meta-data> </receiver>
OnReceive The code logic, such as what I'm using to receive widgets to update the click events defined in OnUpdate () to the Refresh button, to handle the refresh interface requirements,
/** * Receive Intent * /@Override public void OnReceive (context context, Intent Intent) { Super.onreceive (context, intent); String action = Intent.getaction (); if (Action.equals ("Refresh")) { //Refresh widget final Appwidgetmanager mgr = appwidgetmanager.getinstance (context ); Final ComponentName cn = new ComponentName (context, myapplistwidgetprovider.class); MyRemoteViewsFactory.mList.add ("Music" +i); This sentence invokes the ondatasetchanged () method of Remoteviewsfactory in Remoteviewserivce. mgr.notifyappwidgetviewdatachanged (Mgr.getappwidgetids (CN), r.id.widget_list); } else if ( Action.equals (clickaction)) { //Click an item in the ListView in Wdiget to display a toast prompt. Toast.maketext (Context, Intent.getstringextra ("content"), Toast.length_short). Show (); i=i+1; }
3onenabled (Context context)
when Wdiget is available to be dragged into the desktop, we can usually do some variable initial work.
@Override public void onenabled (context context) { //TODO auto-generated method stub super.onenabled ( context); Toast.maketext (context, "user adds widget to desktop", toast.length_short). Show ();
4 ondeleted (),widgets are removed, and here we typically use to release some object and view resources to help prevent memory leaks.
@Override public void ondeleted (context context, int[] appwidgetids) { //TODO auto-generated method stub. Toast.maketext (context, "user removed Widget from desktop", toast.length_short). Show (); Super.ondeleted (context, appwidgetids); }
5 ondisabled ()Widgets are not clickable when the widget is dragged, and the widget is available when the drag operation is stopped.
two creating RemoteviewsfactoryThe remote view factory is used to return remoteviews, which works through Adater, where we call MyRemoteViewsFactory.mList.add () and add data to the ListView on the widget.
public class Myremoteviewsfactory implements Remoteviewsfactory {private final Context mcontext; public static list<string> mlist = new arraylist<string> (); /* Constructor */Public Myremoteviewsfactory (context context, Intent Intent) {mcontext = Context; }/* * Myremoteviewsfactory call execution, this method execution time exceeds 20 seconds return error. * If the time-consuming task should be processed in ondatasetchanged or Getviewat */@Override public void OnCreate () {//data needs to be displayed mlist . Add (""); for (int i = 0; i < 5; i++) {Mlist.add ("item" + i);} }/* * When calling the Notifyappwidgetviewdatachanged method, this method is triggered * For example: myremoteviewsfactory.notifyappwidgetviewdatachanged (); */@Override public void ondatasetchanged () {}/* * This method does not have to say, here write clean resources, release memory operation */@Overrid e public void OnDestroy () {mlist.clear (); }/* Returns the number of collections */@Override public int GetCount () {return mlist.size (); }/* * created and populated, at the specified index bitThe displayed view, this is similar to Baseadapter's GetView */@Override public remoteviews getviewat (int position) {if (position < 0 | | Position >= mlist.size ()) return null; String content = mlist.get (position); Create a View final remoteviews RV = new Remoteviews (Mcontext.getpackagename (), r.layout.my_w in the current index position to display Idget_layout_item); Set the content to be displayed Rv.settextviewtext (R.ID.WIDGET_LIST_ITEM_TV, content); Populate Intent, populate pendingintent Intent Intent created in appwdigetprovider = new Intent (); Incoming clickstream data Intent.putextra ("content", content); Rv.setonclickfillinintent (R.ID.WIDGET_LIST_ITEM_TV, intent); return RV; }/* Displays a "load" View. The default view */@Override public remoteviews Getloadingview () {return null will be used when returning null; }/* * The number of different view definitions. The default is 1 (I always use the default value) */@Override public int getviewtypecount () {return 1; }/* Returns the current index. */@Override public long getitemid (int position) {return position; }/* * Returns TRUE if the ID provided by each item is stable, that is, they do not change at run time. ) */@Override public boolean hasstableids () {return true; }
The three Remoteviewsserviceremoteviewsservice subclasses provide remoteviewsfactory for populating the Remote Collection view.
Specifically, its subclass Remoteviewsservice is a remote service adapter that can request remoteviews to manage remoteviews services. We inherit remoteviewsservice to get a view factory,
@TargetApi (build.version_codes. Honeycomb) public class Myremoteviewsservice extends Remoteviewsservice {@Overridepublic remoteviewsfactory Ongetviewfactory (Intent Intent) { return new Myremoteviewsfactory (This.getapplicationcontext (), Intent);}}
Four Additions Widet Base property Configuration 1 Add widget Profile We added a description XML for the widget, a new XML file directory under Res/, and a new Widget_info.xml file, specifying the minimum width and height for the widget as follows and browse the underlying view, including its specific layout files. Specific introduction Please look at the article---widget principle of detailed.
<?xml version= "1.0" encoding= "Utf-8"? ><appwidget-provider xmlns:android= "http://schemas.android.com/apk/ Res/android " android:initiallayout=" @layout/my_widget_layout " android:minheight=" 120DP " android: Minwidth= "280DP" android:previewimage= "@drawable/ic_launcher" android:resizemode= "horizontal|vertical" android:updateperiodmillis= "0" > <!-- sdk1.5 after the Updateperiodmillis has expired, set to 0, loop execution itself in the code implementation. As for the other attributes you can check. In other essays, I also gave the --></appwidget-provider>
2 new XML for the widget resume one actually to load, that is, I see the layout of the view visually. This layout is via Widgetinfo's android:initiallayout= "@layout/my_widget_layout"
property to specify. And the widget describes the information wemanifest.xml <meta-data> tags are used to specify.
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Match_parent "android:layout_height=" 200DP "android:background=" @android: Color/whi TE "android:orientation=" vertical "> <button android:id=" @+id/button_refresh "Android:layout_wid Th= "Wrap_content" android:layout_height= "wrap_content" android:layout_gravity= "Center_horizontal" an droid:background= "@drawable/lite_widget_item_choosed_background_icon" android:textcolor= "@android: Color/white" android:layout_margintop= "2DP" android:text= "Refresh"/> <listview android:id= "@+id/widget_ List "android:layout_width=" Match_parent "android:layout_height=" Wrap_content "Android:cachecolorhint = "#00000000" android:scrollbars= "None"/> <!--the listview here can be replaced by StackView or GridView--></linearlayout >
Through the above steps we simply implemented a widget development step for beginners to learn and communicate, more complex widget logic we will join the network access, some sevice for data interaction, if you want widgets to automatically join the desktop, or widgets that support custom controls, the first thing you can do is turn my app into a system app, and second, rewriteRemoteviews to support our custom view, concrete implementation of the logic behind the introduction, thank you for reading.
Copyright NOTICE: This article for Bo Master original article, please respect the original, reproduced please indicate the address.
Android Widget Development Details (II.)