public class PageActivity extends Activity {
private int numPages = 31;
private TouchImageView[] imageViews = new TouchImageView[numPages];
private String URL = "http://www.smbc-comics.com/comics/201108";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ViewPager viewPager = new ViewPager(this);
for (int i = 0; i < numPages; i++) {
imageViews[i] = new TouchImageView(this);
imageViews[i].setBackgroundResource(R.drawable.blank);
imageViews[i].setMaxZoom(4f);
}
setContentView(viewPager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(2);
}
private class ImagePagerAdapter extends PagerAdapter {
@Override
public int getCount() {
return numPages;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((TouchImageView) object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = PageActivity.this;
String pageURL = URL;
if (imageViews[position].getDrawable() == null) {
ImageFetcher imagefetcher = new ImageFetcher();
imagefetcher.execute(
pageURL + String.format("%02d", position+1) + ".gif",
String.valueOf(position+1));
}
((ViewPager) container).addView(imageViews[position], 0);
return imageViews[position];
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((TouchImageView) object);
imageViews[position].removeCallbacks(null);
}
}
public class ImageFetcher extends AsyncTask<String, Integer, Drawable> {
int fillthisPos;
public Drawable doInBackground(String... urls) {
try {
InputStream is = (InputStream) new URL(urls[0]).getContent();
fillthisPos = Integer.parseInt(urls[1]);
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
return null;
}
}
@Override
protected void onPostExecute(Drawable result) {
super.onPostExecute(result);
imageViews[fillthisPos].setImageDrawable(result);
result = null;
}
}
}
我正在尝试创建一个图像查看器,它可以从给定的 URL 加载图像。上面的代码使用
- TouchImageView 用于对单个图像进行触摸处理。
- ViewPager 和 PageAdapter 让用户移动到下一页。
- 实例化页面时用于下载图像的 Asyn 任务。
当我下载了一些图像时,应用程序崩溃了。我从 DDMS/MAT 检查了图像的位图没有被释放。这是因为我正在破坏的视图没有被 GC 收集,因为它们仍在某处被引用。
我想知道在这种情况下他们是否可以通过某种方式显式释放内存?我尝试从我的代码中删除所有引用,但它仍然没有释放内存。
PS:对不起,我先放代码,我试图把它移下来,但格式搞砸了。