Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android ListView優化

android ListView優化

編輯:關於Android編程

android ListView優化是通過復用歷史緩存實現的。listview對應的數據適配器一般用自定義的BaseAdapter子類,復用歷史緩存提高性能。示例代碼如下:

1、listView數據適配器

/**
	 * 待處理請假信息的數據適配器類
	 * @author yqq
	 *
	 */
	private  class LeaveInfoAdapter extends BaseAdapter{
		
	
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mleaveInfos.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return mleaveInfos.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public 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("測試",info.toString());
			holder.name.setText(info.getName());
			holder.workIdAndDepartment.setText("(工號:"+info.getWorkId()+"部門:"+info.getDepartment()+")");
			holder.leaveinfo.setText(info.getLeaveInfo());
			holder.date.setText("假期起止:"+info.getLeaveData()+"\n");
			holder.endDate.setText("-"+info.getEndleaveDate());
			
			return view;
		}
		
		
	}
	
	private static class ViewHolder{
		TextView name;//員工姓名顯示控件
		TextView workIdAndDepartment;//員工工號和部門顯示
		TextView leaveinfo;//員工請假信息
		TextView date;//員工請假日期
		TextView endDate;
		
	}
	
	
2、每項數據顯示的布局
leave_info_item.xml



     
            

            

                

                

                
                 

                

               
            
           
     
     

    

3、利用異步任務加載數據

/**
	 * 使用異步加載數據,填充待處理請假信息listView
	 */
	private void fillData(){
		new AsyncTask() {

		

			@Override
			protected void onPostExecute(Void result) {
				
				if(mAdapter==null){
					mAdapter=new LeaveInfoAdapter();
					//設置數據適配器
					mLVleaveInfos.setAdapter(mAdapter);
					Log.i("測試", "異步任務顯示後台獲得數據庫數據");
					}
				else {
					mAdapter.notifyDataSetChanged();
					
				}
				
				
				
				super.onPostExecute(result);
			}

			@Override
			protected Void doInBackground(Void... params) {
				//獲得要顯示的數據
				mleaveInfos=mLeaveInfosDao.findAll();
				if (mleaveInfos==null) {
					Toast.makeText(HomeActivity.this,"請假數據不存在或是已經清除!", 500).show();
					
					
				}
				
				Log.i("測試", "異步任務後台獲得數據庫數據"+mleaveInfos.size());
				
				return null;
			}
		}.execute();
		
		
	}
	

4、為列表每項綁定事件監聽

mLVleaveInfos.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView parent, View view,
					int position, long id) {
				Object object=mLVleaveInfos.getItemAtPosition(position);
				Log.i("同意測試",object+"");
				if(object instanceof LeaveInfo){
					tmpInfo=(LeaveInfo)object;
					Log.i("同意測試",tmpInfo.toString());
					showAcceptOrNo();
				}
				
				
				
			}});

5、列表的其他監聽和分頁加載對於本地數據不需要分頁加載,對於服務器端數據應該分頁加載節省流量。

//下拉列表的時候分頁加載數據
		mRubishSms.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				switch (scrollState) {
				//在下拉列表空閒的時候顯示數據
				case OnScrollListener.SCROLL_STATE_IDLE:
					//獲得分頁加載的每頁最大值
					int position=mRubishSms.getLastVisiblePosition();
					int total=0;
					if(mInfos!=null){
						// total=maxNum;
						total=mInfos.size();
						
					}
					 
					if(position==total-1){
						//到達該分頁加載的末尾位置
						offset+=maxNum;
						if(offset>totalNums){
							Toast.makeText(RubishSmsActivity.this,"數據已經加載完,沒有更多的數據了...", 300).show();
							return;
							
						}
						//異步任務加載數據
						fillData();
						
					}
					
					
					break;

				
				}
				
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				
			}
		});
		
		fillData();
		
		//每個條目綁定監聽
		mRubishSms.setOnItemClickListener(new OnItemClickListener() {

			View m_view=View.inflate(RubishSmsActivity.this,R.layout.show_rubish_sms_operation,null);
			@Override
			public void onItemClick(AdapterView parent, View view,
					int position, long id) {
				//獲得條目對應的每個對象
				 
			Object object=mRubishSms.getItemAtPosition(position);
			if(object instanceof RubishSmsInfo){
				final RubishSmsInfo info=(RubishSmsInfo) object;
				//對對象的操作1、刪除2、恢復到收件箱3、加入黑名單
				Dialog builder=new Dialog(RubishSmsActivity.this);
				builder.setTitle("提示");
				builder.setContentView(m_view);
				
				//刪除
				((TextView)m_view.findViewById(R.id.tv_delete)).setOnClickListener(new OnClickListener() {
					
					@Override
					public 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();
						}
						
					
						
					}
				});
				//恢復到收件箱
				((TextView)m_view.findViewById(R.id.tv_recovery_sms)).setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						
					}
						
				});
				//加入黑名單
				((TextView)m_view.findViewById(R.id.tv_add_black_number)).setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						
						
					}
				});
				
				builder.show();
				
			}
				
				
				
				
				
			}
			
		});
		
		
	}
	



6、BaseExpandableListAdapter示例demo:

public class CommonNumberActivity extends Activity {
	private ExpandableListView elv;
	private List groupNames;
	private Map> childrenCacheInfos;

	@Override
	protected 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() {
			
			@Override
			public 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 {

		// 返回多少個分組
		@Override
		public int getGroupCount() {
			// return CommonNumDao.getGroupCount();
			groupNames = CommonNumDao.getGroupInfos();
			return groupNames.size();
		}

		@Override
		public int getChildrenCount(int groupPosition) {// 0 開始
			List childreninfos;
			if (childrenCacheInfos.containsKey(groupPosition)) {
				childreninfos = childrenCacheInfos.get(groupPosition);
			} else {
				childreninfos = CommonNumDao
						.getChildrenInfosByPosition(groupPosition);
				childrenCacheInfos.put(groupPosition, childreninfos);
			}
			return childreninfos.size();
		}

		@Override
		public Object getGroup(int groupPosition) {
			return null;
		}

		@Override
		public Object getChild(int groupPosition, int childPosition) {
			return null;
		}

		@Override
		public long getGroupId(int groupPosition) {
			return 0;
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			return 0;
		}

		@Override
		public boolean hasStableIds() {
			return false;
		}

		@Override
		public 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;
		}

		@Override
		public 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(18);
			tv.setTextColor(Color.BLUE);
//			tv.setText(CommonNumDao.getChildInfoByPosition(groupPosition,
//					childPosition));
			tv.setText(childrenCacheInfos.get(groupPosition).get(childPosition));
			return tv;
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			return true;
		}

	}
}

7、BaseAdapter數據適配器的另一種用法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;//常用功能顯示
	 private GVAdapter mAdapter;
	 
	 private String[] items={"清理加速","話費流量","騷擾攔截","防吸費","支付保镖","手機殺毒"};
	 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};
	public OftenUseFunctionActivity() {
		// TODO Auto-generated constructor stub
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.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() {

			@Override
			public 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","清理加速");
					}
					break;
				case 1:
					if(D){
						Log.i("OftenUseFunctionActivity","話費流量");
						}
					break;
				case 2:
					if(D){
						Log.i("OftenUseFunctionActivity","騷擾攔截");
						
						}
					Intent intent2=new Intent(OftenUseFunctionActivity.this,StopAnonyActivity.class);
					startActivity(intent2);
					break;
				case 3:
					if(D){
						Log.i("OftenUseFunctionActivity","防吸費");
						}
					break;
				case 4:
					if(D){
						Log.i("OftenUseFunctionActivity","支付保镖");
						}
					break;
				case 5:
					Intent intent6=new Intent(OftenUseFunctionActivity.this,KillVirusActivity.class);
					startActivity(intent6);
					
					if(D){
						Log.i("OftenUseFunctionActivity","手機殺毒");
						}
					break;

				
				}
				
			}
			  
		});
		
	}


	//采用功能的數據適配器
    private class GVAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return items.length;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public 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;//功能圖標
    	TextView tvFunName;//功能描述
    	
    }

}


home_item.xml



	
    

    





  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved