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

Android開發ListView適配器優化

編輯:關於android開發

  Adapter的作用就是ListView界面與數據之間的橋梁,當列表裡的每一項顯示到頁面時,都會調用Adapter的getView方法返回一個View。

  優化的思路兩種:

  1. View的重用 
  View的每次創建是比較耗時的,因此對於getview方法傳入的convertView應充分利用 != null的判斷

  2.ViewHolder的應用
  View的findViewById()方法也是比較耗時的,因此需要考慮只調用一次,之後就用View.getTag()方法來獲得ViewHolder對象

  下面是優化後的代碼供參考:

  public class MyAdapter extends BaseAdapter {
           private Context mContext;
           private LayoutInflater mInflater;
 
           public MyAdapter(Context context) {
               this.mContext = context;
               mInflater = LayoutInflater.from(mContext);
           }
 
           public int getCount() {
 
               return mmsList.size();
           }
 
           public Object getItem(int arg0) {
 
               return arg0;
           }
 
           public long getItemId(int arg0) {
 
               return arg0;
           }
 
           public View getView(int position, View convertView, ViewGroup parent) {
 
               ViewHolder holder = null;
               if (convertView == null) {
 
                   holder = new ViewHolder();
 
                   convertView = mInflater.inflate(R.layout.mmslistitem, null);
                   holder.img = (ImageView) convertView.findViewById(R.id.mmsflag);
                   holder.subject = (TextView) convertView.findViewById(R.id.mmssubject);
                   holder.date = (TextView) convertView.findViewById(R.id.mmsdate);
 
                   convertView.setTag(holder);
 
               } else {
 
                   holder = (ViewHolder) convertView.getTag();
               }
                MMSDBItem mmsItem = mmsList.get(position);
 
               holder.subject.setText(mmsItem.getSubject());
               String today = DateFormat.format("yyyy-MM-dd",System.currentTimeMillis()).toString();
               String dateStr = DateFormat.format("yyyy-MM-dd kk:mm",mmsItem.getDate()).toString();
  
               holder.date.setText(dateStr);
 
               if (mmsItem.getFlag() == 0) {
                   holder.img.setBackgroundResource(R.drawable.new_message_32);
               } else {
                   holder.img.setBackgroundResource(R.drawable.message_already_read_32);
               }
 
               return convertView;
           }
 
           public final class ViewHolder {
               public ImageView img;
               public TextView subject;
               public TextView date;
           }
       }

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