提高顯示布局文件的性能 4 - 提升ListView的性能
Making ListView Scrolling Smooth [使得ListView滾動平滑]
使得滾動ListView平滑的關鍵在與保持AP的UI thread與複雜的操作隔離。
確保另起一個Thread來處理Disk IO,network access或者SQL access.
為了測試AP的狀態,可以enable
為了測試AP的狀態,可以enable
StrictMode
.(Android
ICS 4.0上已經默認開啟了StrickMode)Use a Background Thread [使用後台線程]
使用後台線程,這樣可以使得UI線程可以專注於描繪UI。大多數時候,AsycnTask實現了一種簡單把需要做的事情與main thread隔離的方法。
[關於如何使用AsyncTask,請參考官方詳解,或者參看本人前麵一篇文章:使用AsyncTask來處理一些簡單的需要後台處理的動作]
下麵是一個例子:
- // 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);
executeOnExecutor()
來替代execute(),這樣係統會根據當前設備的內核數量同時進行多個任務。Hold View Objects in a View Holder [如何使用View Holder來Hold住view對象]
你的程序在滾動ListView的時候也許會重複頻繁的call findViewById(),這樣會降低性能。
你仍然需要查找到這些組件並更新它,避免這樣的重複,我們可以使用ViewHolder的設計模式。
A ViewHolder對象存放每一個View組件於Layout的tag屬性中,因此我們可以立即訪問tag中的組件從而避免重複call findViewById()。
A ViewHolder對象存放每一個View組件於Layout的tag屬性中,因此我們可以立即訪問tag中的組件從而避免重複call findViewById()。
下麵是定義了一個ViewHolder的例子:
- static class ViewHolder {
- TextView text;
- TextView timestamp;
- ImageView icon;
- ProgressBar progress;
- int position;
- }
- 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);
最後更新:2017-04-04 07:03:07