android listviewロードピクチャエラー(ずれ)
16065 ワード
詳細
と書く
今晩、ある友达に绍介されて、私は文章を见て、androidの中でlistviewが画像をロードして间违った问题を解决して、见てから、感じがよくて、自分もこの问题に出会って、しかしどのように手をつけて、この文章を见て、私の问题は解决して、同时に作者にも感谢します.
今お腹が空いたら作者の文章を投稿して、みんなに共有します.
と書く
1、スレッドプールを採用する
2、メモリキャッシュ+ファイルキャッシュ
3、メモリキャッシュの中でネット上の多くはSoftReferenceを採用してスタックのオーバーフローを防止して、ここで厳格に最大JVMメモリの1/4しか使用できないことを制限します
4、ダウンロードした画像をスケーリングして、メモリの消耗を減らす
具体的なコードについて説明します.メモリキャッシュクラスのコードを先に置くjava:
public class MemoryCache {
最後に最も重要なロード画像のクラス、ImageLoader.java
と書く
メインフローはメモリキャッシュから検索し,再スレッドがなければファイルキャッシュから検索してもなく指定したurlから検索しbitmapを処理し,最後にUIを次の方法で更新する.
最後に注意したいのは、権限を加えることです.ネットワーク、sdcardなどの権限. testlistview.rar (183.3 KB) ダウンロード回数:248
と書く
今晩、ある友达に绍介されて、私は文章を见て、androidの中でlistviewが画像をロードして间违った问题を解决して、见てから、感じがよくて、自分もこの问题に出会って、しかしどのように手をつけて、この文章を见て、私の问题は解决して、同时に作者にも感谢します.
今お腹が空いたら作者の文章を投稿して、みんなに共有します.
と書く
1、スレッドプールを採用する
2、メモリキャッシュ+ファイルキャッシュ
3、メモリキャッシュの中でネット上の多くはSoftReferenceを採用してスタックのオーバーフローを防止して、ここで厳格に最大JVMメモリの1/4しか使用できないことを制限します
4、ダウンロードした画像をスケーリングして、メモリの消耗を減らす
具体的なコードについて説明します.メモリキャッシュクラスのコードを先に置くjava:
public class MemoryCache {
private static final String TAG = "MemoryCache";
//
// LinkedHashMap true map , LRU
// ,
private Map cache = Collections
.synchronizedMap(new LinkedHashMap(10, 1.5f, true));
// , 0,
private long size = 0;// current allocated size
//
private long limit = 1000000;// max memory in bytes
public MemoryCache() {
// use 25% of available heap size
setLimit(Runtime.getRuntime().maxMemory() / 4);
}
public void setLimit(long new_limit) {
limit = new_limit;
Log.i(TAG, "MemoryCache will use up to " + limit / 1024. / 1024. + "MB");
}
public Bitmap get(String id) {
try {
if (!cache.containsKey(id))
return null;
return cache.get(id);
} catch (NullPointerException ex) {
return null;
}
}
public void put(String id, Bitmap bitmap) {
try {
if (cache.containsKey(id))
size -= getSizeInBytes(cache.get(id));
cache.put(id, bitmap);
size += getSizeInBytes(bitmap);
checkSize();
} catch (Throwable th) {
th.printStackTrace();
}
}
/**
* ,
*
*/
private void checkSize() {
Log.i(TAG, "cache size=" + size + " length=" + cache.size());
if (size > limit) {
//
Iterator> iter = cache.entrySet().iterator();
while (iter.hasNext()) {
Entry entry = iter.next();
size -= getSizeInBytes(entry.getValue());
iter.remove();
if (size <= limit)
break;
}
Log.i(TAG, "Clean cache. New size " + cache.size());
}
}
public void clear() {
cache.clear();
}
/**
*
*
* @param bitmap
* @return
*/
long getSizeInBytes(Bitmap bitmap) {
if (bitmap == null)
return 0;
return bitmap.getRowBytes() * bitmap.getHeight();
}
}
SoftReference, , 。
public class MemoryCache {
private Map> cache = Collections
.synchronizedMap(new HashMap>());
public Bitmap get(String id) {
if (!cache.containsKey(id))
return null;
SoftReference ref = cache.get(id);
return ref.get();
}
public void put(String id, Bitmap bitmap) {
cache.put(id, new SoftReference(bitmap));
}
public void clear() {
cache.clear();
}
}
FileCache.java
public class FileCache {
private File cacheDir;
public FileCache(Context context) {
// SD SD LazyList
// SD
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
cacheDir = new File(
android.os.Environment.getExternalStorageDirectory(),
"LazyList");
else
cacheDir = context.getCacheDir();
if (!cacheDir.exists())
cacheDir.mkdirs();
}
public File getFile(String url) {
// url hashCode
String filename = String.valueOf(url.hashCode());
// Another possible solution
// String filename = URLEncoder.encode(url);
File f = new File(cacheDir, filename);
return f;
}
public void clear() {
File[] files = cacheDir.listFiles();
if (files == null)
return;
for (File f : files)
f.delete();
}
}
最後に最も重要なロード画像のクラス、ImageLoader.java
public class ImageLoader {
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map imageViews = Collections
.synchronizedMap(new WeakHashMap());
//
ExecutorService executorService;
public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
}
// listview ,
final int stub_id = R.drawable.stub;
//
public void DisplayImage(String url, ImageView imageView) {
imageViews.put(imageView, url);
//
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else {
//
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, ImageView imageView) {
PhotoToLoad p = new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url) {
File f = fileCache.getFile(url);
//
Bitmap b = decodeFile(f);
if (b != null)
return b;
// url
try {
Bitmap bitmap = null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
// decode ,
private Bitmap decodeFile(File f) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
}
return null;
}
// Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i) {
url = u;
imageView = i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad) {
this.photoToLoad = photoToLoad;
}
@Override
public void run() {
if (imageViewReused(photoToLoad))
return;
Bitmap bmp = getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if (imageViewReused(photoToLoad))
return;
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
// UI
Activity a = (Activity) photoToLoad.imageView.getContext();
a.runOnUiThread(bd);
}
}
/**
*
*
* @param photoToLoad
* @return
*/
boolean imageViewReused(PhotoToLoad photoToLoad) {
String tag = imageViews.get(photoToLoad.imageView);
if (tag == null || !tag.equals(photoToLoad.url))
return true;
return false;
}
// UI
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
bitmap = b;
photoToLoad = p;
}
public void run() {
if (imageViewReused(photoToLoad))
return;
if (bitmap != null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
public static void CopyStream(InputStream is, OutputStream os) {
final int buffer_size = 1024;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
} catch (Exception ex) {
}
}
}
と書く
メインフローはメモリキャッシュから検索し,再スレッドがなければファイルキャッシュから検索してもなく指定したurlから検索しbitmapを処理し,最後にUIを次の方法で更新する.
a.runOnUiThread(...);
:
ImageLoader imageLoader=new ImageLoader(context);
...
imageLoader.DisplayImage(url, imageView);
ListView adapter getView() , GridView。
adapter :
class MyAdapter extends BaseAdapter{
private String urls[];
private Context context;
public int getCount() {
return urls.length;
}
public void setData(String[] urls) {
this.urls = urls;
}
public Object getItem(int position) {
return urls[position];
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null){
holder = new ViewHolder();
convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.listview_item, null);
holder.imageView = (ImageView) convertView.findViewById(R.id.imageview);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
System.out.println(" --------------position--------==== " + position);
// imageLoader adapter
imageLoader.displayImage(urls[position], holder.imageView);
return convertView;
}
class ViewHolder{
ImageView imageView;
}
}
は最後に注意したいのは、権限を加えることです.ネットワーク、sdcardなどの権限.