我有以下方法,它有一个用户可以左右滑动的ImageSwitcher。所选图像显示在屏幕中央。我已经为低内存手机上的高分辨率图像做了一些图像缩放,但是当从左到右快速滑动时我仍然遇到Bitmap OutOfMemoryEexception。我想转换行mSwitcher.setImageURI(myUri);
(这是导致OOME的行)使用弱引用,以便它可以自动进行垃圾回收。我怎样才能做到这一点?这是性能优化此方法的最佳方法吗?
由于
方法:
public void onItemSelected(AdapterView parent, View v, int position, long id) {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyAppName");
File[] cachedOnSDImages = mediaStorageDir.listFiles();
countArray = new Integer[cachedOnSDImages.length];
fileArray = new String[cachedOnSDImages.length];
fileArray[position] = cachedOnSDImages[position].getAbsolutePath();
Uri myUri = Uri.parse(fileArray[position]);
mSwitcher.setImageURI(myUri); // weakly reference myUri in this line
this.currentpos = position;
}
我应该添加mSwitcher在这里实例化:
private void makeSwitcher() {
mSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
mSwitcher.setFactory(this);
mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_in));
mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_out));
}
答案 0 :(得分:4)
import java.lang.ref.WeakReference;
public class ReferenceTest {
public static void main(String[] args) throws InterruptedException {
WeakReference r = new WeakReference(new String("I'm here"));
WeakReference sr = new WeakReference("I'm here");
System.out.println("before gc: r=" + r.get() + ", static=" + sr.get());
System.gc();
Thread.sleep(100);
// only r.get() becomes null
System.out.println("after gc: r=" + r.get() + ", static=" + sr.get());
}
}
这就是如何在Java中使用弱引用 - 但这也意味着它不适用于您的情况,因为切换器必须显式接受WeakReference对象而不是URI。