How adapter data changes the existing view and its case

Source: Internet
Author: User

First, let's talk about the inheritance relationship of the specific class of the adapter, as shown in

Adapte serves as a bridge between adapterview and view. The adapter loads view (such as the data to be displayed in listview and girdview ). The data to be displayed in the related view is completely decoupled from the view. The data to be displayed in the view is obtained and displayed from the adapter. The adapter is responsible for dividing the actual data into views (each data corresponds to a view) let girdview and other similar components to display these views ,. That is to say, the data to be displayed in the view depends on the adapter, and the changes in the view (for example, deleting a listview or adding an item) also depend on the changes in the data in the adapter. This means that when the data in the adapter changes, the corresponding view (such as listview) also changes accordingly. When the data in the adapter changes, the view must also be notified, and the view is re-painted to display the view with the changed data.

The adapter has the following responsibilities:

1) Adapt source data to one view

2) send a notification when the data changes (send a notification to the observer, and then the observer responds accordingly, in the Observer mode) to make the relevant components (girdview) make changes on the page display.


Some codes of the adapter are as follows:

Public interface adapter {/*** registers the observer and notifies * The observer when the data in the adapter changes. The observer calls onchanged () method to respond accordingly */void registerdatasetobserver (datasetobserver observer);/*** cancel the registered observer object */void unregisterdatasetobserver (datasetobserver observer ); /*** adapt the data in the adapter to one view. Each piece of data corresponds to one view, which is used to display the data and finally display it by girdview and other related components. The getcount () method determines how many views will be generated */view getview (INT position, view convertview, viewgroup parent );}

We can see that the parent interface of adapter defines the method for registering the observer. Next we will look at what the observer has done: the observer here is an extension class of the datasetobserver abstract class. This abstract class provides two methods:

Public abstract class datasetobserver {// call Public void onchanged () {// do nothing} public void oninvalidated () {// do nothing} when the data source changes }}

So how is the observer associated with the adapter? In fact, the observer object is placed in an arraylist set. This set is encapsulated in the abstract class observable <t>. You can see the source code of this class:

Public abstract class observable <t >{// Save the protected final arraylist set of the observer object <t> mobservers = new arraylist <t> (); // register the public void registerobserver (T observer) {If (Observer = NULL) {Throw new illegalargumentexception ("the observer is null. ");} synchronized (mobservers) {If (mobservers. contains (observer) {Throw new illegalstateexception ("Observer" + observer + "is already registered. ");} mobservers. add (observer) ;}}// Delete the registered observer public void unregisterobserver (T observer) {If (Observer = NULL) {Throw new illegalargumentexception ("the observer is null. ");} synchronized (mobservers) {int Index = mobservers. indexof (observer); If (Index =-1) {Throw new illegalstateexception ("Observer" + observer + "was not registered. ");} mobservers. remove (INDEX) ;}// clear all observer public void unregisterall () {synchronized (mobservers) {mobservers. clear ();}}}
You can see through the source code that observervable <t> is mainly responsible for adding and deleting added observers! This abstract class also has a subclass datasetobservable: This class provides two methods on the basis of inheriting the features of the parent class. These two methods are used to send notifications to a series of observers, so that all the observers in the class can execute onchanged () or oninvalidated () to execute specific actions. The source code is as follows:

Public class datasetobservable extends observable <datasetobserver> {// call this method when the data source changes to allow the view to respond to public void policychanged () {synchronized (mobservers) {for (INT I = mobservers. size ()-1; I> = 0; I --) {mobservers. get (I ). onchanged () ;}} public void policyinvalidated () {synchronized (mobservers) {for (INT I = mobservers. size ()-1; I> = 0; I --) {mobservers. get (I ). oninvalidated ();}}}}

Through the above description, we know that the work of the observer object is indirectly sent by datasetobservable to inform and execute the observer's onchange method. After reading this, we can see that the observer is still not associated with the corresponding adapter and how the adapter sends a notification when the data changes. The following describes the source code of baseadapter:


Public abstract class baseadapter implements listadapter, spinneradapter {// This object is used to register the observer private final datasetobservable mdatasetobservable = new datasetobservable (); Public Boolean hasstableids () {return false ;} // register the public void registerdatasetobserver (datasetobserver observer) {mdatasetobservable. registerobserver (observer);} // Delete the public void unregisterdatasetobserver (datasetobserver observer) {mdatasetobservable. unregisterobserver (observer);} // call this method when the data source changes. Public void policydatasetchanged () {mdatasetobservable. policychanged ();} public void policydatasetinvalidated () {mdatasetobservable. notifyinvalidated ();}

Obviously, baseadapter contains a datasetobservable reference mdatasetobservable. According to the preceding instructions, the object represented by this reference contains several observers, the method for registering an observer is the registerdatasetobserver method of baseadapter. By reading the source code, you can find that this class provides the yydatasetchanged () method. When the data in the data source or adapter changes, you must manually call this method to initiate a notification !!!! So far, we have found the method to send notifications to the observer. It is exactly the notifydatasetchanged () method.

The above only describes how to notify the observer when data changes along the context of the program. What has been done by the onchange method implemented by the observer is not explained. These are implemented by different observer subclasses. We will not discuss them here. The following describes how to display the data in the adapter in the view.

One of the responsibilities of the adapter is to organize the data source into one view and return a view object. How to organize it is implemented by getview of the adapter method, this method is actually called when the onmeasure () method is executed, and then specifically called in the obtainview method. Programmers engaged in Android development have to deal with this method. I will not repeat it here.

After the data is put into the adapter, the data is finally presented using the setadapter () method of girdview (or this document uses girdview as an example in listview. Perhaps careful readers will find that they have not added an observer to their adapter during their own development? It's just a simple setadapter (), so you don't have to worry about anything? Otherwise, you will know what setadapter has done.


Public void setadapter (listadapter adapter) {// clear the mdatasetobserver object if (madapter! = NULL & mdatasetobserver! = NULL) {madapter. unregisterdatasetobserver (mdatasetobserver);} // clears all previous data and initializes some necessary parameters resetlist (); mrecycler. clear (); // reset the adapter madapter = adapter; // initialize the position of the last selected item: moldselectedposition = invalid_position; // initialize the position of the last selected row, that is: index of the selected row: moldselectedrowid = invalid_row_id; // abslistview # setadapter will update choice mode states. super. setadapter (adapter); If (madapter! = NULL) {// record the number of items in girdview molditemcount = mitemcount; // The data of items in the current girdview = mitemcount = madapter. getcount (); // The data has changed mdatachanged = true; // check focus checkfocus (); // register the observer mdatasetobserver = new adapterdatasetobserver (); madapter. registerdatasetobserver (mdatasetobserver); mrecycler. setviewtypecount (madapter. getviewtypecount (); int position; // determine whether to find the position of selectable from the end. // lookforselectableposition indicates that the second parameter is useless if (mstackfrombottom) from the method implementation) {position = lookforselectableposition (mitemcount-1, false);} else {position = lookforselectableposition (0, true);} // select the number, the row and current girdview ID setselectedpositionint (position) are recorded; // select the next setnextselectedpositionint (position); // check whether the selected position changes checkselectionchanged ();} else {checkfocus (); // nothing selected checkselectionchanged () ;}// recharge layout requestlayout ();}

Through the source code above, we can find that the adapterdatasetobserver object will be registered every time setadapter is called (33 lines of code above), so that the response can be processed when the adapter changes.

Let's take a look at what the specific observer has done:

Class adapterdatasetobserver extends adapterview <listadapter>. adapterdatasetobserver {@ override public void onchanged () {// note that the main logic is in super. in the onchanged () method, super. onchanged (); If (mfastscroller! = NULL) {mfastscroller. onsectionschanged () ;}@ override public void oninvalidated () {super. oninvalidated (); If (mfastscroller! = NULL) {mfastscroller. onsectionschanged ();}}}

The onchange () method calls the onchange () method of the parent class. The main logic for responding to data changes lies in the onchange () method of the parent class, first, let's take a look at the specific implementation of this method for the parent class:

class AdapterDataSetObserver extends DataSetObserver {        private Parcelable mInstanceState = null;        @Override        public void onChanged() {            mDataChanged = true;            mOldItemCount = mItemCount;            mItemCount = getAdapter().getCount();            if (AdapterView.this.getAdapter().hasStableIds() && mInstanceState != null                    && mOldItemCount == 0 && mItemCount > 0) {                AdapterView.this.onRestoreInstanceState(mInstanceState);                mInstanceState = null;            } else {                rememberSyncState();            }            checkFocus();            requestLayout();        }}

Finally, requestlayout () is executed to re-layout the page to respond to data changes. So far, we have completed the description of changing the current view by changing the adapter data.


The following is a case study:

There are

1

Note that the 12 data items are saved in the girdview. When I click Edit, the page changes to as shown in:

2

The following describes the specific implementation of this effect.

1) the adapter code is as follows:

Public class collectionitemadapter extends baseadapter {private vector <collection> collections; public static final int edit_status = 0; // when the value is zero, the editing state is public static final int unedit_status =-1; // Private int deleposition = unedit_status; // Delete the flag public int getdeleposition () {return deleposition;} public void setdeleposition (INT deleposition) {This. deleposition = deleposition;} public vector <collection> Getcollections () {return collections;} public void setcollections (vector <collection> collections) {This. Collections = collections ;}@ overridepublic int getcount () {If (collections! = NULL) {return collections. Size () ;}// todo auto-generated method stubreturn 0 ;}@ overridepublic collection getitem (INT position) {If (collections! = NULL) {return collections. get (position);} // todo auto-generated method stubreturn NULL;} @ overridepublic long getitemid (INT position) {// todo auto-generated method stubreturn position ;} @ overridepublic view getview (INT position, view convertview, viewgroup parent) {viewitem = NULL; If (convertview = NULL) {viewitem = new viewitem (); convertview = app. getlayoutinflater (). inflate (R. layout. collection_item, null); viewitem. IMG = (imageview) convertview. findviewbyid (R. id. item_img); viewitem. name = (textview) convertview. findviewbyid (R. id. item_name); viewitem. editbg = (imageview) convertview. findviewbyid (R. id. collection_edit_bg); convertview. settag (viewitem);} else {viewitem = (viewitem) convertview. gettag ();} viewitem. IMG. setimageresource (R. drawable. no_pic_small); Collection collection = This. getitem (position); viewitem. name. settext (collection. getname (); imageloader. getinstance (). displayimage (collection. getpicurl (), viewitem. IMG, app. getoptionssmall (); viewitem. IMG. setvisibility (view. visible); If (deleposition = edit_status) {// indicates the editing status. // display and delete the background image viewitem. editbg. setvisibility (view. visible);} else {// hide and delete the background image viewitem. editbg. setvisibility (view. gone) ;}return convertview;} Private Static class viewitem {imageview IMG; textview name; imageview editbg; Public String tostring () {return name. gettext (). tostring ();}}}
Note that the adapter has a deleposition to indicate whether it is in the editing status. When it is in the non-editing status, the running result is 1. When you click Edit, The delepoition is in the editing status, and the page effect is

2. When you click Edit, the response event is:


// Set the delete flag collectionadapter. setdeleposition (collectionitemadapter. unedit_status); // notify the observer of collectionadapter. yydatasetchanged ();


2) The collection_item.xml configuration file is as follows:

<? XML version = "1.0" encoding = "UTF-8"?> <Relativelayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: layout_width = "fill_parent" Android: layout_height = "fill_parent"> <relativelayout Android: layout_width = "@ dimen/wiki_item_w" Android: layout_height = "@ dimen/wiki_item_h"> <! -- Poster --> <relativelayout Android: layout_width = "match_parent" Android: layout_height = "match_parent" Android: padding = "@ dimen/pading_17"> <imageview Android: id = "@ + ID/item_img" Android: layout_width = "fill_parent" Android: layout_height = "fill_parent" Android: focusable = "false" Android: src = "@ drawable/test"/> </relativelayout> <! -- Basemap of the program name --> <relativelayout Android: layout_width = "match_parent" Android: layout_height = "match_parent" Android: padding = "@ dimen/pading_15"> <imageview Android: id = "@ + ID/item_bg_img" Android: layout_width = "fill_parent" Android: layout_height = "fill_parent" Android: focusable = "false" Android: src = "@ drawable/item_txt_bg"/> </relativelayout> <! -- Focus frame image --> <imageview Android: Id = "@ + ID/collection_focus" Android: layout_width = "match_parent" Android: layout_height = "match_parent" Android: background = "@ drawable/item_focus_selecter"/> <! -- The background image is in the editing status, and the visibility is gone. When you click "edit", the image is visible. --> <relativelayout Android: layout_width = "match_parent" Android: layout_height = "match_parent" Android: padding = "@ dimen/pading_19"> <imageview Android: Id = "@ + ID/collection_edit_bg" Android: layout_width = "match_parent" Android: layout_height = "match_parent" Android: focusable = "false" Android: Background = "@ drawable/record_collection_edit_selecter" Android: visib Ility = "gone"/> </relativelayout> <! -- Program name --> <TV. huan. EPG. vod. qclt. UI. widget. scrollforevertextview Android: Id = "@ + ID/item_name" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content" Android: layout_alignparentbottom = "true" Android: layout_marginbottom = "@ dimen/users" Android: layout_marginleft = "@ dimen/collection_item_name_margin_right" Android: layout_marginright = "@ dimen/users" Android: ellipsize = "marquee" android: gravity = "center" Android: marqueerepeatlimit = "marquee_forever" Android: singleline = "true" Android: textcolor = "@ drawable/font_color_selector" Android: textsize = "@ dimen/font_20"/> </relativelayout>

Thank you for your criticism when you are new to Android.

How adapter data changes the existing view and its case

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.