Overview
ListView: A list view that can be slid vertically.
The Setemptyview () interface inherits from the parent class Adapterview of the ListView. It is conceivable that when the ListView is empty, Emptyview is displayed, which has an indirect connection to the data adapter of the ListView.
Usage Scenarios
Lists are used extensively for data model displays with the same data types, and you can customize the list to meet the actual requirements.
This article mainly introduces the List.setemptyview () interface. Using the scenario, when a client displays a Listview,listview in the current display window, it needs to be displayed by adapter to associate the data to the list. This will bring up a scene, that is, when the data inside the adapter or adapter is not set, if you give the user a friendly prompt, improve the user experience.
Android official source has provided such an interface, through this interface, in the process of using the ListView, using the intrinsic logic to help us achieve this function, reduce the code, so that the code is more clear and understandable.
Implementation method:
There are two ways to add Emptyview, one is to write the Emptyview directly in the creation of the layout, the disadvantage of which is lack of flexibility. Another way is to create emptyview by code, which is more flexible than the layout to add, and can be customized emptyview, dynamic modification. Of course, even if you add emptyview by layout, you can add it again through the code.
1. layout file Implementation Emptyview
<ViewGroup…<TextView android:id="@+id/emptyView" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:text="@string/tip_of_empty" android:visibility="gone" />…</ViewGroup>
2. Implementation in code
textview emptyview = new TextView (context) < span> emptyview.setlayoutparams (New Layoutparams (Layoutparams _parent, Layoutparams _parent)) ; emptyview.settext (R.string .tip _of_empty) emptyview.setvisibility (View) ; (viewgroup) list.getparent ()) (Emptyview) list.setemptyview (emptyview) ;
Note: Adding Emptyview has a precondition that the added emptyview must exist in the parent container of the ListView, or in the same view tree, to take effect, which involves the principle of list.setemptyview ().
Point in time
- ListView Initialization
When the list is initialized, the Emptyview is created and added to the ListView, which has a bad user experience, that is, before adding data to the ListView, or before the network request data is returned, the ListView will hide, display Emptyview, When the data arrives and updates the ListView, the Emptyview will be hidden, and the ListView will show a flash effect. Adding Emptyview at the point in time of initialization is not recommended.
- Set Adapter
The time-point setting Emptyview will have the same display effect in some cases, when adapter is empty, the associated ListView will be the same as the ListView initialization, and when the data request is complete, the current data condition can be displayed exactly when the adapter is set. This is the third point of time.
- Listen for network request return data
Adding Emptyview after fetching the data can properly react to the current state and is also the best way to use it.
This time will mainly introduce one of the point is the ListView initialization, others please go to see the source code, and finally will find that the principle is the same.
Implementation principle
The
Emptyview shows the principle that when adapter is null, or if the data of adapter is empty, that is, when the ListView has no data to display, the The Listvewi is set to View.gone, Emptyview is set to View.visable, and the logic is reversed when the data is not empty. This effect can be achieved only if Emptyview is in the current layout level, as shown in.
ListView Initialization:
Source code implementation in Listactivity.java: As an example of the official website, you can see its specific usage and logic, including when the Emptyview is added, and the process relationship Emptyview added.
Listactivity created layout hierarchy: Listactivity, as the name implies, the activity maintains a ListView for the consumer, but when the listactivity is created, it does not appear in the layout hierarchy.
Therefore, to see the source code of Listactivity, the source, in the use of listactivity, you need to call Setcontentview ()/setlistadapter () to initialize.
as can be seen from the source code, the Ensurelist () method is called in the Setlistadapter method. The
in the Ensurelist () method will judge the Listactivity maintained ListView, and if NULL, Setcontentview will be called, otherwise return to execution. Then look at Setcontentview. After the
Setcontentview () method was called, it was found that there was no result we wanted, no initialization of the ListView, and so on, deadlocked. But we looked at the source carefully and found that window was called in Setcontentview (). Setcontentview (). In various ways, it was discovered that the activity class implements the Window.callback interface, and when the activity calls Setcontentview (), it callbacks the Oncontentchanged () method.
in Oncontentchanged (), go back to initialize Listview,emptyview.
The specific process added through Listactivity,emptyview is:
Next look at Listview.setemptyview () to realize the source code.
SOURCE Analysis:
/** * Sets the view to show if the adapter is empty * / @android. View. Remotableviewmethod Public void Setemptyview(View Emptyview) {Memptyview = Emptyview;//If not explicitly specified this view are important for accessibility. if(Emptyview! =NULL&& emptyview.getimportantforaccessibility () = = Important_for_accessibility_auto) {Emptyview.setimporta Ntforaccessibility (Important_for_accessibility_yes); }FinalT adapter = Getadapter ();Final BooleanEmpty = ((adapter = =NULL) || Adapter.isempty ()); Updateemptystatus (empty); }
In Setemptyview, you can see two points, that is, the Memptyview in the ListView is a reference relationship to the incoming view object, and the 2nd is: the definition of empty, when Adapter==null, or Adapter.isempty ( ), and then pass in Updateemptystatus ().
/** * Update The status of the list based on the empty parameter. If empty is true and * we had an empty view, display it. In all of the other cases, make sure that the ListView are VISIBLE and that the empty view is GONE (if it's not null). */ Private void Updateemptystatus(BooleanEmpty) {if(Isinfiltermode ()) {empty =false; }if(empty) {if(Memptyview! =NULL) {memptyview.setvisibility (view.visible); Setvisibility (View.gone); }Else{//If The caller just removed our empty view, make sure the list view is visibleSetvisibility (view.visible); }//We are now GONE, so pending layouts would not be dispatched. // Force One, here, make sure, the state of the list matches // The state of the adapter. if(mdatachanged) { This. OnLayout (false, Mleft, Mtop, Mright, Mbottom); } }Else{if(Memptyview! =NULL) memptyview.setvisibility (View.gone); Setvisibility (view.visible); } }
The principle of the Updateemptystatus () method is equivalent to the schematic diagram drawn earlier, and the logic of Emptyview is realized by setting the visibility property of the view. However, Setempty just add an interface update, when there is data, adapter must notify the ListView, and then to update the current visibility properties, so go to see and adapter related two data update methods.
/** * Sets the data behind this ListView. * * The adapter passed to this method is wrapped by a {@link wrapperlistadapter}, * depending on the ListView Features currently in use. For instance, adding * headers and/or footers would cause the adapter to be wrapped. * * @param Adapter The ListAdapter which is responsible for maintaining the * data backing this Li St and for producing a view to represent an * item in that data set. * * @see #getAdapter () */ @Override Public void Setadapter(ListAdapter adapter) {if(Madapter! =NULL&& Mdatasetobserver! =NULL) {madapter.unregisterdatasetobserver (mdatasetobserver); } resetlist (); Mrecycler.clear ();if(Mheaderviewinfos.size () >0|| Mfooterviewinfos.size () >0) {Madapter =NewHeaderviewlistadapter (Mheaderviewinfos, Mfooterviewinfos, adapter); }Else{Madapter = adapter; } moldselectedposition = Invalid_position; Moldselectedrowid = invalid_row_id;//Abslistview#setadapter'll update Choice mode states. Super. Setadapter (adapter);if(Madapter! =NULL) {mareallitemsselectable = madapter.areallitemsenabled (); Molditemcount = Mitemcount; Mitemcount = Madapter.getcount (); Checkfocus (); Mdatasetobserver =NewAdapterdatasetobserver (); Madapter.registerdatasetobserver (Mdatasetobserver); Mrecycler.setviewtypecount (Madapter.getviewtypecount ());intPositionif(Mstackfrombottom) {position = Lookforselectableposition (Mitemcount-1,false); }Else{position = Lookforselectableposition (0,true); } setselectedpositionint (position); Setnextselectedpositionint (position);if(Mitemcount = =0) {//Nothing selectedCheckselectionchanged (); } }Else{mareallitemsselectable =true; Checkfocus ();//Nothing selectedCheckselectionchanged (); } requestlayout (); }
Setadapter () method, there are two points, one is Checkfocus, the other is to register a data observer for adapter, the following source will be introduced, when the adapter data sent changes, the Observer's OnChanged () method will be recalled.
Checkfocus () Source code:
voidCheckfocus () {FinalT adapter = Getadapter ();Final BooleanEmpty = Adapter = =NULL|| Adapter.getcount () = =0;Final Booleanfocusable =!empty | | Isinfiltermode ();//The order in which we set focusable on touch mode/focusable may matter //For the client, see View.setfocusableintouchmode () Comments for more //Details Super. Setfocusableintouchmode (focusable && mdesiredfocusableintouchmodestate);Super. setfocusable (focusable && mdesiredfocusablestate);if(Memptyview! =NULL) {Updateemptystatus (adapter = =NULL) || Adapter.isempty ()); } }
As you can see, the Checkfocus () method calls Updateemptystatus (), which updates the Emptyview when the data adapter is set.
Next look at the registered REGISTERDATASETOBSERVER data Observer Source:
publicvoidregisterDataSetObserver(DataSetObserver observer) { mDataSetObservable.registerObserver(observer); }
The logic of the Setadapter () method ends, and then the Setemptyview () and Setadapter () methods are only called once when the data is initialized, and when the data is sent to change, You need to manually update adapter call notifydatasetchanged ().
Notifydatasetchanged () Source code:
/** * Notifies the attached observers that the underlying data have been changed * and any View reflecting the Data set should refresh itself. */ Public void notifydatasetchanged() {mdatasetobservable.notifychanged (); }adapter calls the Notifydatasetchanged () method, essentially calling Mdatasetobservable. Notifychanged () method. Continue to follow./** * Invokes {@link datasetobserver#onchanged} on each observer. * Called when the contents of the data set has changed. The recipient * would obtain the new contents the next time it queries the data set. */ Public void notifychanged() {synchronized(mobservers) {//Since onChanged () is implemented by the app, it could do anything, including //removing itself from {@link Mobservers}-and that could cause problems if //An iterator are used on the ArrayList {@link mobservers}. //To avoid such problems, just March thru the list in the reverse order. for(inti = mobservers.size ()-1; I >=0; i--) {mobservers.get (i). onChanged (); } }}
In the Notifychanged () method, all registered data observers are traversed, and the onchanged () method of the observer is recalled, the source can be seen, in the adapter source code, created an internal class adapterdatasetobserver, The OnChanged () method is re-written.
class adapterdatasetobserver extends datasetobserver { PrivateParcelable minstancestate =NULL; @Override Public voidOnChanged () {mdatachanged =true; Molditemcount = Mitemcount; Mitemcount = Getadapter (). GetCount ();//Detect The case where a cursor that is previously invalidated has //been repopulated with new data. if(Adapterview. This. Getadapter (). Hasstableids () && minstancestate! =NULL&& Molditemcount = =0&& Mitemcount >0) {Adapterview. This. Onrestoreinstancestate (Minstancestate); Minstancestate =NULL; }Else{remembersyncstate (); } checkfocus (); Requestlayout (); }}
There are two points in onChanged (), a point is mdatachanged, in the Updateemptystatus () method to determine the state of the variable, when True, the ListView layout size is updated, while the onChanged () The Mdatachanged method is set to True to notify the layout update, and the other is to call the Checkfocus () method, which indirectly calls Updateemptystatus () for Emptyview updates.
At this point, the basic logic of Emptyview's setup is already clear and summarized. The Emptyview update is primarily performed in Updateemptystatus (), after initializing the adapter of the ListView and the Callback Adapter.notifydatasetchanged () method after the data is updated, Its essence is also the callback Notifydatasetchanged () method.
Summarize
- Setempty principle: Dynamically update the Visibility property of the ListView and Emptyview.
- Conditions of Use: Emptyview is required in the layout hierarchy of the ListView.
- Note: When using code to add Emptyview, it is important to note that you cannot loop to add Emptyview because Emptyview is added to the layout hierarchy, and the ListView simply holds a reference.
Purely individual learning summary, there is not the right place, affirmation, thank you!
Android Listview.setemptyview