Android ListView Optimization

Source: Internet
Author: User

Android ListView Optimization

Android ListView optimization is implemented by reusing the historical cache. The data adapter corresponding to listview generally uses the 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 ;}@ Overri Depublic 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 = mleaveInfos. get (position); Log. I ("test", info. toString (); holder. name. setText (info. getName (); holder. workIdAndDepartment. setText ("(employee ID:" + info. getWorkId () + "Department:" + info. getDepartment () + ")"); holder. leaveinfo. setText (info. getLeaveInfo (); holder. date. setText ("holiday start and end:" + info. getLeaveData () + "\ n"); holder. endDate. setText ("-" + info. getEndleaveDate (); return view ;}} private static class ViewHolder {TextView name; // The employee name display control TextView workIdAndDepartment; // The employee ID 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

 
      
              
               
                   
                    
                    
                     
                    
                               
                   
           
  
 
3. load data using asynchronous tasks

/*** Load data asynchronously and fill in the waiting for processing leave information listView */private void fillData () {new AsyncTask
 
  
() {@ Overrideprotected void onPostExecute (Void result) {if (mAdapter = null) {mAdapter = new LeaveInfoAdapter (); // set the data adapter mLVleaveInfos. setAdapter (mAdapter); Log. I ("test", "Retrieving Database Data in the background of asynchronous task display");} else {mAdapter. yydatasetchanged ();} super. onPostExecute (result) ;}@ Overrideprotected Void doInBackground (Void... params) {// obtain the data to be displayed mleaveInfos = mLeaveInfosDao. findAll (); if (mleaveInfos = null) {Toast. makeText (HomeActi Rejected. this, "the leave data does not exist or has been cleared! ", 500 ). show ();} Log. I ("test", "Retrieving Database Data in the background of asynchronous tasks" + mleaveInfos. size (); return null1_0000.exe cute ();}
 

4. Bind event listening to each item in the list

MLVleaveInfos. setOnItemClickListener (new OnItemClickListener () {@ Overridepublic void onItemClick (AdapterView
 Parent, View view, int position, long id) {Object object = mLVleaveInfos. getItemAtPosition (position); Log. I ("Agree To test", object + ""); if (object instanceof LeaveInfo) {tmpInfo = (LeaveInfo) object; Log. I ("Agree To test", tmpInfo. toString (); showAcceptOrNo ();}}});

5. other monitoring and paging loading of the list do not require paging loading for local data, but the server data should be loaded by page to save traffic.

// Load the data mRubishSms by page in the drop-down list. setOnScrollListener (new OnScrollListener () {@ Overridepublic void onScrollStateChanged (AbsListView view, int scrollState) {switch (scrollState) {// display the data case OnScrollListener when the drop-down list is idle. SCROLL_STATE_IDLE: // obtain the maximum value of each page loaded by page. int position = mRubishSms. getLastVisiblePosition (); int total = 0; if (mInfos! = Null) {// total = maxNum; total = mInfos. size () ;}if (position = total-1) {// the position at the end of the page loading is offset + = maxNum; if (offset> totalNums) {Toast. makeText (RubishSmsActivity. this, "the data has been loaded and there is no more data... ", 300 ). show (); return ;}// load data fillData () ;}break ;}@overridepublic void onScroll (AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) in asynchronous tasks) {// TODO Auto-generated method stub}); fillData (); // each entry is bound to listen to 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) {// obtain the Object object Object = mRubishSms corresponding to the entry. getItemAtPosition (position); if (object instanceof RubishSmsInfo) {final RubishSmsInfo info = (RubishSmsInfo) object; // operation on the object 1. Delete 2. Restore to inbox 3. Add the blacklist Dialog builder = new Dialog (RubishSmsActivity. this); builder. setTitle ("prompt"); 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. yydatasetchanged () ;}}); // restore to the 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. demo of BaseExpandableListAdapter:

Public class CommonNumberActivity extends Activity {private ExpandableListView elv; private List
 
  
GroupNames; private Map
  
   
> ChildrenCacheInfos; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); childrenCacheInfos = new HashMap
   
    
> (); 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 {// number of returned groups @ Overridepublic int getGroupCount () {// return CommonNumDao. getGroupCount (); groupNames = CommonNumDao. getGroupInfos (); return groupNames. size () ;}@ Overridepublic int getChildrenCount (int groupPosition) {// 0 Start List
    
     
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 (25); 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, ViewGrou P parent) {TextView TV; if (convertView! = Null & convertView instanceof TextView) {TV = (TextView) convertView;} else {TV = new TextView (getApplicationContext ();} TV. setTextSize (18); TV. setTextColor (Color. BLUE); // TV. setText (CommonNumDao. getChildInfoByPosition (groupPosition, // childPosition); TV. setText (childrenCacheInfos. get (groupPosition ). get (childPosition); return TV ;}@ Overridepublic boolean isChildSelectable (int groupPosition, int childPosition) {return true ;}}}
    
   
  
 

7. Another usage demo of BaseAdapter:

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 functions: private GVAdapter mAdapter; private String [] items = {"Clean up acceleration ", "phone traffic", "Harassment interception", "anti-fees", "Payment guard", "Mobile Phone anti-virus"}; 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. public 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); // 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 Intent (OftenUseFunctionActivity. this, CleanCacheActivity. class); startActivity (intent); if (D) {Log. I ("OftenUseFunctionActivity", "clear acceleration") ;}break; case 1: if (D) {Log. I ("OftenUseFunctionActivity", "call 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-fees") ;}break; case 4: if (D) {Log. I ("OftenUseFunctionActivity", "Payment guard");} break; case 5: Intent intent6 = new Intent (OftenUseFunctionActivity. this, KillVirusActivity. class); startActivity (intent6); if (D) {Log. I ("OftenUseFunctionActivity", "cell phone Antivirus") ;}break ;}});} // use the function of the data adapter 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

 
     
      
  
 





Related Article

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.