android ListView最佳化

來源:互聯網
上載者:User

標籤:java   listview 最佳化 事件監聽   

android ListView最佳化是通過複用曆史緩衝實現的。listview對應的資料配接器一般用自訂的BaseAdapter子類,複用曆史緩衝提高效能。範例程式碼如下:

1、listView資料配接器

/** * 待處理請假資訊的資料配接器類 * @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("測試",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

<?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"    android: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="match_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="姓名"                    android:textColor="#ff0000"                    android:textSize="15sp" />                <TextView                    android:id="@+id/tv_leave_info"                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                    android:layout_below="@+id/tv_name"                    android:paddingTop="8dp"                    android:text="請假理由"                    android:textSize="20sp" />                <TextView                    android:id="@+id/tv_date"                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                    android:layout_above="@+id/tv_leave_info"                    android:layout_alignParentRight="true"                    android:text="日期"                    android:textColor="#000000"                    android:textSize="10sp" />                 <TextView                    android:id="@+id/tv_endtime"                    android:layout_width="wrap_content"                    android:layout_height="wrap_content"                  android:layout_below="@+id/tv_date"                                   android:layout_alignParentRight="true"                    android:text="日期2"                    android:textColor="#000000"                    android:textSize="10sp" />                <TextView                    android:id="@+id/tv_workid_depart"                    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="姓名和部門"                    android:textColor="#0000ff"                    android:textSize="13sp" />                           </RelativeLayout>                </LinearLayout>         <View          android:layout_width="match_parent"        android:layout_height="2dp"        android:background="@android:drawable/divider_horizontal_dark"        /></LinearLayout>
3、利用非同步任務載入資料

/** * 使用非同步載入資料,填充待處理請假資訊listView */private void fillData(){new AsyncTask<Void,Void,Void>() {@Overrideprotected void onPostExecute(Void result) {if(mAdapter==null){mAdapter=new LeaveInfoAdapter();//設定資料配接器mLVleaveInfos.setAdapter(mAdapter);Log.i("測試", "非同步任務顯示後台獲得資料庫資料");}else {mAdapter.notifyDataSetChanged();}super.onPostExecute(result);}@Overrideprotected 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() {@Overridepublic 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() {@Overridepublic 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;}}@Overridepublic 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);@Overridepublic 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() {@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();}}});//恢複到收件匣((TextView)m_view.findViewById(R.id.tv_recovery_sms)).setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {}});//加入黑名單((TextView)m_view.findViewById(R.id.tv_add_black_number)).setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {}});builder.show();}}});}



6、BaseExpandableListAdapter樣本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 {// 返回多少個分組@Overridepublic int getGroupCount() {// return CommonNumDao.getGroupCount();groupNames = CommonNumDao.getGroupInfos();return groupNames.size();}@Overridepublic int getChildrenCount(int groupPosition) {// 0 開始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(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, 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;}@Overridepublic 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}@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","清理加速");}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{@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;//功能表徵圖    TextView tvFunName;//功能描述        }}


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最佳化

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.