嘗試使用setTag()
。檢查了這一點
BitmapCache.java
public class BitmapCache {
private static SparseArray<Bitmap> _bitmapCache = new SparseArray<>();
public static void fillBitmapCache(@NonNull Resources resources) {
if (null == _bitmapCache)
_bitmapCache = new SparseArray<>();
if (_bitmapCache.indexOfKey(R.drawable.amazon) < 0)
_bitmapCache.append(R.drawable.amazon, BitmapFactory.decodeResource(resources, R.drawable.amazon));
if (_bitmapCache.indexOfKey(R.drawable.app_me) < 0)
_bitmapCache.put(R.drawable.app_me, BitmapFactory.decodeResource(resources, R.drawable.app_me));
if (_bitmapCache.indexOfKey(R.drawable.borabora) < 0)
_bitmapCache.put(R.drawable.borabora, BitmapFactory.decodeResource(resources, R.drawable.borabora));
if (_bitmapCache.indexOfKey(R.drawable.dubai) < 0)
_bitmapCache.put(R.drawable.dubai, BitmapFactory.decodeResource(resources, R.drawable.dubai));
}
public static Bitmap getAt(int position) {
return get(keyAt(position));
}
public static int keyAt(int position) {
return _bitmapCache.keyAt(position);
}
public static Bitmap get(@DrawableRes int resId) {
return _bitmapCache.get(resId);
}
public static boolean has(@DrawableRes int resId) {
return _bitmapCache.indexOfKey(resId) < 0;
}
public static void append(@DrawableRes int resId, @NonNull Resources resources) {
_bitmapCache.append(resId, BitmapFactory.decodeResource(resources, resId));
}
public static void put(@DrawableRes int resId, @NonNull Resources resources) {
_bitmapCache.put(resId, BitmapFactory.decodeResource(resources, resId));
}
public static int size() {
return _bitmapCache.size();
}
}
活動首先
private void showImage() {
BitmapCache.fillBitmapCache(getResources());
m_oHandler = new Handler();
Runnable oRunnable = new Runnable() {
int i = 0;
@Override
public void run() {
img.setImageBitmap(BitmapCache.getAt(i));
img.setTag(BitmapCache.keyAt(i));
i++;
if (i >= BitmapCache.size()) {
i = 0;
}
img.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (null != v.getTag()) {
int resId = (int) v.getTag();
Intent intent = new Intent(MainActivity.this, Second.class);
intent.putExtra("BitmapImage", resId);
}
}
});
m_oHandler.postDelayed(this, 6000);
}
};
m_oHandler.postDelayed(oRunnable, 6000);
}
次活動
private void displayImageOnSecond() {
Bundle bundle = getIntent().getExtras();
int resId = bundle.getInt("BitmapImage", 0);
if (resId > 0) {
secondImage.setImageBitmap(BitmapCache.get(resId));
}
}
此外,我建議使用ViewPager
和自定義爲自動旋轉,而不是目前使用的一種。如果Activity
已被破壞
你也可以傳遞數組列表的位置,使ArrayList的靜態的,所以你可以在全球使用它
Runnable
可能導致內存泄漏。 –如何................. – Raghav
定義res/values/array.xml文件並僅將位置傳遞給下一個活動。在下一個活動中訪問數組並獲取圖像:) –