The content is Bo master according to the book knocked out, Bo main code word very hard, reproduced please indicate the source, after the subsequent content will code out.
Preface: listview--list, as a very important way to display, whether in the Web or mobile platform, is a very good, not open or missing display information tools. In Android, the ListView control takes over this burden, and in a lot of situations we need to use this control. Although in the Android 5.X era, Recyclerview in many places are gradually replacing the ListView, but the use of the ListView is still very wide, it is not easy to shake the status of Big Brother. The following is a description of the ListView common optimization techniques.
Increase efficiency with Viewholder mode
Viewholder mode is an important method to improve the efficiency of the ListView. The Viewholder mode takes full advantage of the ListView's view caching mechanism, and avoids instantiating the control by Findviewbyid () each time it calls GetView (). It is tested that using viewholder will increase efficiency by more than 50%. Using the Viewholder mode to optimize the ListView is very simple, just define an inner class Viewholder in the custom adapter, and use the controls in the layout as member variables, as shown in the code below.
publicfinalclass ViewHolder { public ImageView img; public TextView title;}
Next, as long as the cache can be reused through the view caching mechanism in the GetView () method, the full use of Viewholder to create the instance code for the ListView adapter is shown below.
ImportAndroid.content.Context;ImportAndroid.view.LayoutInflater;ImportAndroid.view.View;ImportAndroid.view.ViewGroup;ImportAndroid.widget.BaseAdapter;ImportAndroid.widget.ImageView;ImportAndroid.widget.TextView;ImportJava.util.List;/********************************************** author:blankj on 2016/7/23 15:39 * blog:http://blankj.com* e-mail : [Email protected]*********************************************/ Public class viewholderadapter extends baseadapter { PrivateList<string> Mdata;PrivateLayoutinflater Minflater; Public Viewholderadapter(context context, list<string> data) { This. mdata = data; Minflater = Layoutinflater.from (context); }@Override Public int GetCount() {returnMdata.size (); }@Override PublicObjectGetItem(intPosition) {returnMdata.get (position); }@Override Public Long Getitemid(intPosition) {returnPosition }@Override PublicViewGetView(intPosition, View Convertview, ViewGroup parent) {Viewholder Viewholder =NULL;//Determine if the cache if(Convertview = =NULL) {Viewholder =NewViewholder ();//Instantiate layout by LayoutinflaterConvertview = Minflater.inflate (R.layout.viewholder_item,NULL); Viewholder.img = (ImageView) Convertview.findviewbyid (R.id.imageview); Viewholder.title = (TextView) Convertview.findviewbyid (R.id.textview); Convertview.settag (Viewholder); }Else{//Find the cached layout by tagViewholder = (Viewholder) convertview.gettag (); }//Set the view to be displayed for the control in the layoutViewHolder.img.setBackgroundResource (R.mipmap.ic_launcher); ViewHolder.title.setText (Mdata.get (position));returnConvertview; } Public Final class viewholder { PublicImageView img; PublicTextView title; }}
The effect is simple, which is a simple ListView, as shown in.
Set up separation lines between items
The various items in the ListView can be differentiated by setting a separator line, and the system provides two properties such as divider and dividerheight to help us implement this function. These two properties also allow you to control the separation line between the ListView and its height. Of course, the divider line can be set not just as a color, but also as a picture resource, with the code for dividing lines as shown below.
android:divider="@color/colorAccent"android:dividerHeight="10dp"
The above code is implemented as shown in the effect.
In special cases, you can set the divider line to be transparent when you set the divider to the following code.
android:divider="@null"
Hide the scroll bar of a ListView
The default ListView, when scrolling, displays a scroll bar on the right, indicating where the current slide is, and we can set the ScrollBars property to control the scrollbar state of the ListView. In particular, when the ScrollBars property is set to None, the ListView does not scroll or scroll, and the code is shown below.
android:divider="@null"
Cancel item Click Effect of ListView
When you click on an item in the ListView, a click Effect appears by default, The android5.x is a ripple effect, while the version under android5.x is a change in the background color effect, but can be modified by modifying the Listselector property to cancel the feedback effect after the Click, the code is as follows.
android:listSelector="#00000000"
Of course, you can also use the transparent color of Android to achieve this effect, the code is as follows.
android:listSelector="@android:color/transparent"
Set the ListView to be displayed in the first few items
The ListView is displayed as item, which is displayed by default on the first item, and can be implemented with the following code when you need to specify the item to be displayed specifically.
mListView.setSelection(N);
where n is the nth item that needs to be displayed.
Of course, this method is similar to Scrollto, which is the instantaneous completion of the movement. In addition, you can use the following code to achieve smooth movement.
mListView.smoothScrollBy(distance,duration);mListView.smoothScrollByOffset(offset);mListView.smoothScrollToPosition(index);
Dynamically modifying the ListView
The data in the ListView needs to change in some cases, but of course you can update the ListView display by re-setting the ListView's adapter, but that also requires retrieving the data again, which is equivalent to refreshing the created ListView, which is obviously not very friendly , and the efficiency is not too high. Therefore, you can use a simpler method to implement the dynamic modification of the ListView, as shown in the code below.
mData.add("new");mAdapter.notifyDataSetChanged();
After modifying the map list passed to adapter, you only need to notify the ListView to change the data source by calling the adapter Notifydatasetchanged () method to complete the dynamic modification of the ListView. However, one thing to note with this approach is that when using the Madapter.notifydatasetchanged () method, it is important to ensure that the data that is passed into the adapter list is the same list and cannot be another object, otherwise the effect cannot be achieved. The following example demonstrates how to dynamically modify a ListView. Add a new item to the original list by clicking the button, and call the Notifydatasetchanged () method to implement the dynamic update of the ListView, as shown in the complete code below.
ImportAndroid.os.Bundle;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.view.View;ImportAndroid.widget.ListView;ImportJava.util.ArrayList; Public class mainactivity extends appcompatactivity {ListView Mlistview; Viewholderadapter Madapter; Arraylist<string> Mdata;@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); Mlistview = (ListView) Findviewbyid (R.id.listview); Mdata =NewArraylist<> (); for(inti =0; I < -; ++i) {Mdata.add (i +""); } Madapter =NewViewholderadapter ( This, Mdata); Mlistview.setadapter (Madapter); Madapter.notifydatasetchanged (); for(inti =0, Len = Mlistview.getcheckeditemcount (); i < Len; i++) {View view = Mlistview.getchildat (i); } } Public void Btnadd(View view) {Mdata.add ("New"); Madapter.notifydatasetchanged (); Mlistview.setselection (Mdata.size ()-1); }}
The effect of the implementation is as shown.
Iterate through all the item in the ListView
The ListView, as a ViewGroup, provides us with a variety of methods for manipulating the sub-view, most commonly using getchildat () to get the I sub view, as shown in the code below.
for (int0, len = mListView.getCheckedItemCount(); i < len; i++) { View view = mListView.getChildAt(i);}
Handling Empty ListView
The ListView is used to show the list data, but when there is no data in the list, the ListView does not display any data or hints, which should be given without data in the light of the need to improve the user experience. Fortunately, the ListView provides a method for--setemptyview (), which allows us to set a default hint for the ListView to display under empty data. The layout settings that contain the ListView are as follows.
<?xml version="1.0"encoding="Utf-8"? ><framelayout xmlns:android="Http://schemas.android.com/apk/res/android"xmlns:tools="Http://schemas.android.com/tools"Android:layout_width="Match_parent"android:layout_height="Match_parent"tools:context="Com.blankj.listviewskill.MainActivity"> <listview android:id="@+id/listview"Android:layout_width="Match_parent"android:layout_height="Match_parent"Android:divider="@null"Android:listselector="@android: Color/transparent"Android:paddingbottom="40DP"/> <imageview android:id="@+id/empty_view"Android:layout_width="Match_parent"android:layout_height="Match_parent"Android:src="@mipmap/ic_launcher"/></framelayout>
In the code, we give the ListView the layout to display when the empty data is set in the following way, as shown in the code below.
mListView.setEmptyView(findViewById(R.id.empty_view));
With the above code, the listview displays a default image when the data is empty, which is used to prompt the user, and is not displayed when there is data.
Sliding monitoring of the ListView
The sliding monitoring of the ListView is the most important technique in the ListView, and many of the rewritten ListView are basically working on the handling of the sliding event, and the different logic processing is done by judging the sliding events. For better and more accurate monitoring of sliding events, developers often need to use auxiliary classes such as gesturedetector gesture recognition, velocitytracker sliding speed detection, and more. Here are two ways to listen to a ListView slide event, one for listening via Ontouchlistener and the other for listening using Onscrolllistener.
Ontouchlistener
Ontouchlistener is a monitoring event in the view, by listening to the coordinates of the three events of Action_down, Action_move, Action_up, the direction of the user's sliding can be judged according to the coordinates, and the corresponding logic is processed in different events. , the usage code for this way is shown below.
Mlistview.setontouchlistener (NewView.ontouchlistener () {@Override Public Boolean OnTouch(View V, motionevent event) {Switch(Event.getaction ()) { CaseMotionevent.action_down://Touch-time Operation Break; CaseMotionevent.action_move://Mobile Operation Break; CaseMOTIONEVENT.ACTION_UP://operation on departure Break; }return false; }});
Onscrolllistener
Onscrolllistener is a listener event in Abslistview, which encapsulates many of the ListView-related information and is more flexible to use. First look at the general usage of Onscrolllistener, as shown in the code below.
Mlistview.setonscrolllistener (NewAbslistview.onscrolllistener () {@Override Public void onscrollstatechanged(Abslistview view,intScrollstate) {Switch(scrollstate) { CaseScroll_state_idle://Slide StopLOG.D ("Test","Scroll_state_idle"); Break; CaseScroll_state_touch_scroll://scrollingLOG.D ("Test","Scroll_state_touch_scroll"); Break; CaseScroll_state_fling://When the finger is thrown, the finger is forced to slide //After leaving the ListView due to inertia continues to slideLOG.D ("Test","Scroll_state_fling"); Break; } }@Override Public void onscroll(Abslistview view,intFirstvisibleitem,intVisibleItemCount,intTotalitemcount) {//scrolling is always calledLOG.D ("Test","Onscroll"); }
There are two callback methods--onscrollstatechanged () and Onscroll () in the
Onscrolllistener.
First Look at the first method onscrollstatechanged (), this method according to its parameter scrollstate to determine the number of callbacks, Scrollstate has the following three modes:
** **scroll_state_ IDLE: When scrolling is stopped.
** **scroll_state_touch_scroll: When scrolling.
** **scroll_state_fling: When the finger is thrown, that is, the finger is forced to slide, and the ListView continues to slide after leaving
when the user does not have a state of finger-throwing, the method will only call back 2 times, or it will be recalled three times, The difference is the state of the finger toss. In general, we will set some flag flags in this method by different states to distinguish between different sliding states for other methods to handle.
Next look at Onscroll () This callback method, which will always be callback when the ListView scrolls, and the next three arguments of type int in the method, which shows the state of the current ListView scroll very precisely, the three parameters are as follows.
** **firstvisibleitem: The ID of the first item that is currently visible (starting at 0)
** **visibleitemcount: The total number of item currently visible.
** **totalitemcount: The total number of item for the entire ListView. The
note here is that the item number that is currently visible, including the item that does not show the full item, is also included in the display Yiche. Through these parameters, it is easy to make some judgments, such as whether to scroll to the last line, you can use the following code to judge, the current visual of another item's ID plus the current visual item's sum equals the total item, that is, scroll to the last line.
if0) { Log.d("Test""滚动到最后一行");}
For example, the following code can be used to determine the direction of scrolling, the code is as follows.
if(firstVisibleItem > lastVisibleItem){ // 上滑}elseif(firstVisibleItem < lastVisibleItem){ // 下滑}lastVisibleItem = firstVisibleItem;
The current scrolling direction is known by a member variable Lastvisibleitem to record the ID of the last visible item and compare it to the ID of the current visual item.
The best way to understand the whole onscrolllistener is to add log to the code and print out the status information for analysis. In the above code, the corresponding log has been added, the comparison of log analysis, will quickly grasp the use of onscrolllistener.
Of course, the ListView also gives us a few encapsulated ways to get information about where the item is currently visible.
// 获取可视区域内最后一个Item的idmListView.getLastVisiblePosition();// 获取可视区域内第一个Item的idmListView.getFirstVisiblePosition();
Project Address →listviewskill
Original address ListView Common optimization techniques (Android Elite biography)
My self-media blog blankj Small station (OJ, Leetcode, Android Development), welcome to stroll.
ListView Common Optimization Tips (Android Elite biography)