Android Developers:使ListView滑動流暢,androidlistview

來源:互聯網
上載者:User

Android Developers:使ListView滑動流暢,androidlistview

流暢滑動ListView的關鍵是保持應用程式的主線程(UI線程)從免於繁重處理。確保你的任何硬碟訪問,網路訪問或者SQL訪問在一個單獨的線程中。為了測試你的應用個程式的狀態,你能啟動StrictMode。 

 使用後台線程 —————————————————————————————————————————————————————————————— 使用一個後台線程(“背景工作執行緒”),從主線程中移除,所以它能專註於繪製UI。在許多情況下,使用AsyTask提供的簡單方式,在主線程之外來執行你的工作。AsyncTask自動隊列儲存所有execute()請求,並連續的執行它們。這個行為對於一個進程是全域的,並且意味著你不需要擔心建立你自己的線程池。  在下面的這個範例程式碼中,AsyncTask是被用於在後台線程中下載圖片,然後一旦完成將它們顯示到UI中。當它們在下載的時候,它也在圖片的位置顯示了一個進度條。 [java]// Using an AsyncTask to load the slow images in a background thread   new AsyncTask<ViewHolder, Void, Bitmap>() {       private ViewHolder v;       @Override       protected Bitmap doInBackground(ViewHolder... params) {           v = params[0];           return mFakeImageLoader.getImage();       }       @Override       protected void onPostExecute(Bitmap result) {           super.onPostExecute(result);           if (v.position == position) {               // If this item hasn't been recycled already, hide the               // progress and set and show the image               v.progress.setVisibility(View.GONE);               v.icon.setVisibility(View.VISIBLE);               v.icon.setImageBitmap(result);           }       }   }.execute(holder);<span style="font-family:Arial,sans-serif; font-size:10pt; color:windowtext"> </span>  從Android3.0開始(API level11),在AsyncTask中有一個額外的功能,這麼你能啟用它來運行在多處理器核心中。替代調用execute()方法,你能調用executeOnExecutor()方法,然後基於可用的核心數,多個請求能在同一時間上運行。  在View Holder中儲存視圖 ——————————————————————————————————————————————————————————————當滑動ListView的時候,你的代碼應該會經常調用findViewById()方法,它會減緩效能。即使Adapter返回一個在填充視圖迴圈使用,你一直需要尋找這個元素並更新他們。一種不錯的使用findViewById()方法的方式,是使用“view holder”設計模型。  ViewHolder對象存放了布局標記地區的視圖組件,所以你能立刻訪問它們,不需要重複的尋找它們。首先,你需要建立一個類來儲存你需要的視圖組。例如: [java] static class ViewHolder {     TextView text;     TextView timestamp;     ImageView icon;     ProgressBar progress;     int position;   }   然後填充這個ViewHolder,並在這個布局中儲存它。 [java]ViewHolder holder = new ViewHolder();   holder.icon = (ImageView) convertView.findViewById(R.id.listitem_image);   holder.text = (TextView) convertView.findViewById(R.id.listitem_text);   holder.timestamp = (TextView) convertView.findViewById(R.id.listitem_timestamp);   holder.progress = (ProgressBar) convertView.findViewById(R.id.progress_spinner);   convertView.setTag(holder);   現在你能快速存取每個視圖,不需要尋找,節省寶貴的處理器時間。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.