Android ListView Optimizer

Source: Internet
Author: User

Android ListView optimizations are implemented by reusing the historical cache. The data adapter for the ListView typically uses a custom baseadapter subclass to reuse the historical cache to improve performance. The sample code is as follows:

1. ListView Data Adapter

/** * Data adapter class for pending leave information * @author YQQ * */private class Leaveinfoadapter extends baseadapter{@Overridepublic int GetCount () {//TODO auto-generated method Stubreturn mleaveinfos.size ();} @Overridepublic Object getItem (int position) {//TODO auto-generated method Stubreturn mleaveinfos.get (position);} @Overridepublic long Getitemid (int position) {//TODO auto-generated method Stubreturn position;} @Overridepublic view GetView (int position, view Convertview, ViewGroup parent) {view view=null; Viewholder holder=null;if (convertview!=null && convertview instanceof linearlayout) {View=convertview;holder = (Viewholder) View.gettag ();} Else{view=view.inflate (Getapplicationcontext (), r.layout.leave_info_item, null); holder=new ViewHolder (); Holder.name= (TextView) View.findviewbyid (r.id.tv_name); holder.workidanddepartment= (TextView) View.findviewbyid ( R.id.tv_workid_depart); holder.leaveinfo= (TextView) View.findviewbyid (r.id.tv_leave_info); holder.date= (TextView) View.findviewbyid (r.id.tv_date); holder.enDdate= (TextView) View.findviewbyid (r.id.tv_endtime); View.settag (holder);} Leaveinfo Info=mleaveinfos.get (position); LOG.I ("Test", info.tostring ()); Holder.name.setText (Info.getname ()); Holder.workIdAndDepartment.setText ("(Work No.:" + Info.getworkid () + "department:" +info.getdepartment () + ")"); Holder.leaveinfo.setText (Info.getleaveinfo ()); Holder.date.setText ("Holidays:" +info.getleavedata () + "\ n"), Holder.endDate.setText ("-" +info.getendleavedate ()); return view;}} private static class Viewholder{textview name;//Employee name Display Control TextView workidanddepartment;//employee work number and department display TextView leaveinfo;/ /employee Leave Information TextView date;//employee leave date TextView endDate;}
2. Layout of each data display
Leave_info_item.xml

<?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=" match_parent "android:orientation=" vertical " > <linearlayout android:layout_width= "match_parent" android:layout_height= "Match_parent" a        ndroid:orientation= "Horizontal" > <imageview android:id= "@+id/iv_headcolor"             Android:layout_width= "Wrap_content" android:layout_height= "80DP" android:src= "@drawable/light_green"/> <relativelayout android:layout_width= "match_parent" android:layout_height= "Ma                Tch_parent "android:layout_marginleft=" 5DP "android:layout_margintop=" 5DP ">                    <textview android:id= "@+id/tv_name" android:layout_width= "Wrap_content" android:layout_height="Wrap_content" android:text= "name" android:textcolor= "#ff0000" Android                    Oid:textsize= "15sp"/> <textview android:id= "@+id/tv_leave_info" Android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:l                    ayout_below= "@+id/tv_name" android:paddingtop= "8DP" android:text= "Reason for leave"                    Android:textsize= "20sp"/> <textview android:id= "@+id/tv_date" Android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" Android Oid:layout_above= "@+id/tv_leave_info" android:layout_alignparentright= "true" Android                 : text= "Date" android:textcolor= "#000000" android:textsize= "10sp"/>           <textview         Android:id= "@+id/tv_endtime" android:layout_width= "Wrap_content" Android:la yout_height= "Wrap_content" android:layout_below= "@+id/tv_date" Android:                    Layout_alignparentright= "true" android:text= "date 2" android:textcolor= "#000000" Android:textsize= "10sp"/> <textview android:id= "@+id/tv_workid_depar                    T "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "                    Android:layout_alignparenttop= "true" android:layout_torightof= "@+id/tv_name" Android:gravity= "Center_horizontal" android:paddingleft= "5DP" android:text= "name and department                           Door "android:textcolor=" #0000ff "android:textsize=" 13sp "/> </relativelayout&gT        </LinearLayout> <view android:layout_width= "match_parent" android:layout_height= "2DP" android:background= "@android:d Rawable/divider_horizontal_dark"/></linearlayout>
3. Loading data with asynchronous tasks

/** * Fill pending leave information using asynchronous load data listview */private void Filldata () {new asynctask<void,void,void> () {@Overrideprotected void OnPostExecute (void result) {if (madapter==null) {madapter=new leaveinfoadapter ();// Set data adapter Mlvleaveinfos.setadapter (Madapter); LOG.I ("Test", "asynchronous task shows background data for database");} else {madapter.notifydatasetchanged ();} Super.onpostexecute (result);} @Overrideprotected void Doinbackground (void ... params) {//Get the data to be displayed Mleaveinfos=mleaveinfosdao.findall (); Mleaveinfos==null) {Toast.maketext (homeactivity.this), "Leave data does not exist or has been cleared!" ",". Show ();} LOG.I ("Test", "asynchronous task backend obtains database data" +mleaveinfos.size ()); return null;}}. Execute ();}

4, for the list of each binding event monitoring

Mlvleaveinfos.setonitemclicklistener (New Onitemclicklistener () {@Overridepublic void Onitemclick (adapterview<? > Parent, View view,int position, long id) {Object object=mlvleaveinfos.getitematposition (position); LOG.I ("Consent test", object+ ""); if (object instanceof leaveinfo) {tmpinfo= (Leaveinfo) object; LOG.I ("Consent Test", tmpinfo.tostring ()); Showacceptorno ();}});

5, the list of other listening and paging load for local data does not require paging, for server-side data should be paged load save traffic.

Drop-down list when the paging load data Mrubishsms.setonscrolllistener (new Onscrolllistener () {@Overridepublic void onscrollstatechanged ( Abslistview view, int scrollstate) {switch (scrollstate) {//Show data case when the drop-down list is idle onscrolllistener.scroll_state_idle:// Gets the maximum per page load for a paginated int position=mrubishsms.getlastvisibleposition (); int total=0;if (minfos!=null) {//total=maxnum;total= Minfos.size ();} if (POSITION==TOTAL-1) {//arrives at the end of the page load Offset+=maxnum;if (offset>totalnums) {Toast.maketext ( Rubishsmsactivity.this, "The data has been loaded, no more data ...". Show (); return;} Asynchronous task Load Data Filldata ();} Break;}} @Overridepublic void Onscroll (abslistview view, int firstvisibleitem,int visibleitemcount, int totalitemcount) {//TODO A uto-generated method stub}}); Filldata ();//per-entry binding listener Mrubishsms.setonitemclicklistener (new Onitemclicklistener () { View m_view=view.inflate (rubishsmsactivity.this,r.layout.show_rubish_sms_operation,null); @Overridepublic void Onitemclick (adapterview<?> parent, View view,int position, long ID) {//Get an entry corresponding to each object of objects Object=mrubishsms.geTitematposition (position); if (object instanceof Rubishsmsinfo) {final rubishsmsinfo info= (rubishsmsinfo) object;// Action on the object 1, delete 2, restore to Inbox 3, blacklist Dialog builder=new Dialog (rubishsmsactivity.this); Builder.settitle ("hint"); Builder.setcontentview (M_view);//Delete ((TextView) M_view.findviewbyid (R.id.tv_delete)). Setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {minfos.remove (info); if (mrubishsmsinfodao==null) { Mrubishsmsinfodao=new Rubishsmsinfodao (Getapplicationcontext ());} Mrubishsmsinfodao.deletesmsinfos (Info), if (madapter==null) {madapter=new rubishsmsinfosadapter (); Mrubishsms.setadapter (Madapter);} Else{madapter.notifydatasetchanged ();}}); /Revert to Inbox ((TextView) M_view.findviewbyid (r.id.tv_recovery_sms)). Setonclicklistener (New Onclicklistener () {@ overridepublic void OnClick (View v) {}});//blacklist ((TextView) M_view.findviewbyid (R.id.tv_add_black_number)). Setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {}}); Builder.show ();}});}



6. Baseexpandablelistadapter Sample Demo:

public class Commonnumberactivity extends Activity {private Expandablelistview elv;private list<string> Groupnames;private Map<integer, list<string>> Childrencacheinfos; @Overrideprotected void OnCreate ( Bundle savedinstancestate) {super.oncreate (savedinstancestate); Childrencacheinfos = new Hashmap<integer, List< String>> (); Setcontentview (r.layout.activity_common_num); ELV = (Expandablelistview) Findviewbyid (R.ID.ELV); Elv.setadapter (New Myadapter ()); Elv.setonchildclicklistener (new Onchildclicklistener () {@Overridepublic Boolean Onchildclick (expandablelistview parent, View v,int groupposition, int childposition, long id) {Intent Intent = new Intent ( ); Intent.setaction (intent.action_dial); String number = Childrencacheinfos.get (groupposition). Get (Childposition). Split ("\ n") [1];intent.setdata (Uri.parse ( "Tel:" +number)); StartActivity (intent); return false;}); Private class Myadapter extends Baseexpandablelistadapter {//returns the number of groupings @overridepublic int GetGroupCount () {//REturn Commonnumdao.getgroupcount (); groupnames = Commonnumdao.getgroupinfos (); return groupnames.size ();} @Overridepublic int getchildrencount (int groupposition) {//0 start list<string> childreninfos;if ( Childrencacheinfos.containskey (groupposition)) {Childreninfos = Childrencacheinfos.get (groupPosition);} else { Childreninfos = Commonnumdao.getchildreninfosbyposition (groupposition); Childrencacheinfos.put (GroupPosition, Childreninfos);} return Childreninfos.size ();} @Overridepublic Object getgroup (int groupposition) {return null;} @Overridepublic Object getchild (int groupposition, int childposition) {return null;} @Overridepublic long getgroupid (int groupposition) {return 0;} @Overridepublic long Getchildid (int groupposition, int childposition) {return 0;} @Overridepublic Boolean hasstableids () {return false;} @Overridepublic View getgroupview (int groupposition, Boolean Isexpanded,view Convertview, ViewGroup parent) {TextView TV if (Convertview!=null&&convertview instanceof TextView) {TV = (TextView) Convertview;} ELSE{TV = new TextView (Getapplicationcontext ());} Tv.settextsize (+); Tv.settextcolor (color.red);//Tv.settext ("" +commonnumdao.getgroupname (groupposition)); Tv.settext ("" + Groupnames.get (groupposition)); return TV;} @Overridepublic view Getchildview (int groupposition, int childposition,boolean islastchild, view Convertview, ViewGroup Parent) {TextView tv;if (convertview!=null&&convertview instanceof TextView) {TV = (TextView) Convertview;} ELSE{TV = new TextView (Getapplicationcontext ());} Tv.settextsize, Tv.settextcolor (Color.Blue);//tv.settext (Commonnumdao.getchildinfobyposition, childposition)); Tv.settext (Childrencacheinfos.get (groupposition). Get (Childposition)); return TV;} @Overridepublic boolean ischildselectable (int groupposition, int childposition) {return true;}}}

7. Another usage of Baseadapter data adapter Demo:

Package Com.example.yqqmobilesafe;import Com.example.yqqmobilesafe.cleanache.cleancacheactivity;import Android.app.activity;import Android.content.intent;import Android.os.bundle;import Android.util.Log;import Android.view.view;import Android.view.viewgroup;import Android.widget.adapterview;import Android.widget.adapterview.onitemclicklistener;import Android.widget.baseadapter;import Android.widget.GridView; Import Android.widget.imageview;import Android.widget.linearlayout;import Android.widget.textview;public class Oftenusefunctionactivity extends Activity {private Boolean d=true; private GridView mgridview;//common features show private gvadapter  Madapter; Private string[] items={"cleanup acceleration", "Charge Flow", "Harassment interception", "anti-suction fee", "Pay Bodyguard", "mobile phone Antivirus"}; Private int[] Icons={r.drawable.exam_frequently_used_tools_icon_clean,r.drawable.exam_frequently_used_tools_icon _net_traffic,r.drawable.exam_frequently_used_tools_icon_block_anoy,r.drawable.exam_frequently_used_tools_icon_ Costguard,r.drawable.exam_frequently_used_tools_icon_guarDpay,r.drawable.exam_frequently_used_tools_icon_malware};p ublic oftenusefunctionactivity () {//TODO Auto-generated constructor stub} @Overrideprotected void OnCreate (Bundle savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate (savedinstancestate); Setcontentview (r.layout.activity_tab_often_use_function);// Data adaptation mgridview= (GridView) This.findviewbyid (r.id.gv_home); madapter=new gvadapter (); Mgridview.setadapter (MAdapter)  ; Setlistener ();} private void Setlistener () {Mgridview.setonitemclicklistener (new Onitemclicklistener () {@Overridepublic void Onitemclick (adapterview<?> parent, View view,int position, long ID) {switch (position) {case 0:intent intent=new int ENT (Oftenusefunctionactivity.this,cleancacheactivity.class); startactivity (intent); if (D) {log.i (" Oftenusefunctionactivity "," cleanup Acceleration ");} Break;case 1:if (D) {log.i ("oftenusefunctionactivity", "Telephone Traffic");} Break;case 2:if (D) {log.i ("oftenusefunctionactivity", "harassment interception"); Intent intent2=new Intent (oftenusefunctionactivity.this,stopanonyActivity.class); startactivity (Intent2); Break;case 3:if (D) {log.i ("oftenusefunctionactivity", "anti-suction fee");} Break;case 4:if (D) {log.i ("oftenusefunctionactivity", "Payment bodyguard"); Break;case 5:intent intent6=new Intent (oftenusefunctionactivity.this,killvirusactivity.class); StartActivity ( INTENT6), if (D) {log.i ("oftenusefunctionactivity", "mobile Antivirus");}  Break;}} });} Data adapter with function Private class Gvadapter extends baseadapter{@Overridepublic int GetCount () {//TODO auto-generated method Stubreturn Items.length;} @Overridepublic Object getItem (int 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) {View View=view.inflate ( Oftenusefunctionactivity.this,r.layout.home_item,null); ImageView ivicon= (ImageView) View.findviewbyid (R.id.iv_ Home_icon); TextView tvfunname= (TextView) View.findviewbyid (r.id.tv_home_function_name); Ivicon.setimageresource (Icons[position]); Tvfunname.settext (Items[position]); return view;} } static class viewholder{ImageView ivicon;//function icon TextView tvfunname;//function Description}}


Home_item.xml

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" wrap_content "    android:layout_height=" 95DP "    android:gravity=" center "    android:background= "@drawable/grid_selector" >    <imageview        android:layout_margintop= "5DP"        android:id= "@+id/iv_home_icon"        android:layout_width= "55DP"        android:layout_height= "45DP"       / >    <textview        android:layout_margintop= "5DP"        android:id= "@+id/tv_home_function_name"        Android:layout_width= "Wrap_content"        android:layout_height= "wrap_content"        android:layout_marginright= "10DP"        android:gravity= "center_vertical"              android:textcolor= "#000000"        android:textsize= "20SP"/ ></LinearLayout>





Android ListView Optimizer

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.