The observer pattern is, for example, setting an observer for a adapter that executes the callback method in the observer when adapter calls the Notifydatasetchaged () method
1 PackageCom.xqx.adapterobserver;2 3 Importandroid.app.Activity;4 ImportAndroid.database.DataSetObserver;5 ImportAndroid.os.Bundle;6 ImportAndroid.view.View;7 Importandroid.widget.*;8 ImportOrg.w3c.dom.Text;9 Ten Importjava.util.ArrayList; One Importjava.util.List; A - Public classMainactivityextendsActivity { - /** the * Called when the activity is first created. - */ - - PrivateArrayadapter<integer>adapter; + PrivateList<integer>list; - PrivateListView ListView; + PrivateTextView text; A at //Create observer - PrivateDatasetobserver Sumobserver =NewDatasetobserver () { - /** - * Called when Adapter's Notifydatasetchanged method executes - */ - @Override in Public voidonChanged () { - Super. onChanged (); to //perform the appropriate action + intsum = 0; - for(inti = 0; I < list.size (); i++) { thesum+=List.get (i); * } $Text.settext ("Total Amount:" +sum);Panax Notoginseng } - the /** + * Called when adapter calls the Notifydatasetinvalidate method execution A */ the @Override + Public voidoninvalidated () { - Super. oninvalidated (); $ //perform the appropriate action $ } - }; - @Override the Public voidonCreate (Bundle savedinstancestate) { - Super. OnCreate (savedinstancestate);Wuyi Setcontentview (r.layout.main); the -List =NewArraylist<integer>(); Wu for(inti = 0; I < 30; i++) { -List.add (0); About } $adapter =NewArrayadapter<integer> ( This, Android. r.layout.simple_list_item_1,list); - //Registered Observer - Adapter.registerdatasetobserver (sumobserver); -Text =(TextView) Findviewbyid (r.id.text); AListView =(ListView) Findviewbyid (R.id.listview); + Listview.setadapter (adapter); the -Listview.setonitemclicklistener (NewAdapterview.onitemclicklistener () { $ @Override the Public voidOnitemclick (adapterview<?> adapterview, view view,intILongl) { theList.set (i,2); the //changes the list item's 0 to the 2 update adapter, the adapter.notifydatasetchanged (); - //after the method is executed, the Datasetobserver Observer observes in } the }); the About } the the @Override the protected voidOnDestroy () { + Super. OnDestroy (); - //Logout Observer the Adapter.unregisterdatasetobserver (sumobserver);Bayi } the } the -Mainactivity.javaActivity
The application of the viewer mode in the shopping cart