public View getView(int position, View convertView, ViewGroup parent) {

 

if(convertView==null){
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.photo_item, null);
holder = new ViewHolder();
holder.photo = (ImageView) convertView.findViewById(R.id.photo_item_image);
holder.photoTitle = (TextView) convertView.findViewById(R.id.photo_item_title);
holder.photoDate = (TextView) convertView.findViewById(R.id.photo_item_date);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
cursor.moveToPosition(position);
Bitmap current = dateCache.get(position);
if(current != null){//如果緩存中已解碼該圖片,則直接返回緩存中的圖片
holder.photo.setImageBitmap(current);
}else {
current = bitmapDecoder.getPhotoItem(cursor.getString(1), 2) ;
holder.photo.setImageBitmap(current);
dateCache.put(position, current);
}

 

holder.photoTitle.setText(cursor.getString(2));
holder.photoDate.setText(cursor.getString(4));
return convertView;
}

 

}
複製代碼
package dev.bestjoy;

 

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
 
public class BitmapDecoder {

 

private static final String TAG = "BitmapDecoder";
private Context context;
public BitmapDecoder(Context context) {
this.context = context;
}

 

public Bitmap getPhotoItem(String filepath,int size) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize=size;
Bitmap bitmap = BitmapFactory.decodeFile(filepath,options);
bitmap=Bitmap.createScaledBitmap(bitmap, 180, 251, true);
//預先縮放,避免即時縮放,可以提高更新率
return bitmap;
}
 
 
}
複製代碼
2.由於Gallery控制項的特點,總有一個item處於當前選擇狀態,我們利用此時進行dataCache中額外不用的bitmap的清理,來釋放記憶體。
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,long id) {

 

releaseBitmap();
Log.v(TAG, "select id:"+ id);
}

 

private void releaseBitmap(){
//在這,我們分別預存儲了第一個和最後一個可見位置之外的3個位置的bitmap
//即dataCache中始終只緩存了(M=6+Gallery當前可見view的個數)M個bitmap
int start = mGallery.getFirstVisiblePosition()-3;
int end = mGallery.getLastVisiblePosition()+3;


 

Log.v(TAG, "start:"+ start);
Log.v(TAG, "end:"+ end);

 

//釋放position<start之外的bitmap資源
Bitmap delBitmap;
for(int del=0;del<start;del++){
delBitmap = dateCache.get(del);
if(delBitmap != null){
//如果非空則表示有緩存的bitmap,需要清理
Log.v(TAG, "release position:"+ del);
//從緩存中移除該del->bitmap的映射
dateCache.remove(del);
delBitmap.recycle();
}
}

 

freeBitmapFromIndex(end);
}

 

/**
* 從某一位置開始釋放bitmap資源
* @param index
*/

 

private void freeBitmapFromIndex(int end) {
//釋放之外的bitmap資源
Bitmap delBitmap;
for(int del =end+1;del<dateCache.size();del++){
delBitmap = dateCache.get(del);
if(delBitmap != null){
dateCache.remove(del);
delBitmap.recycle();
Log.v(TAG, "release position:"+ del);
}

 

}
}
arrow
arrow
    全站熱搜

    戮克 發表在 痞客邦 留言(0) 人氣()