Code example for ImageSwitcher

Methods: getTag, setImageDrawable, setTag

0
     * @param imageSwitcher 
     * @return 
     */ 
    private static LocalImageSwitcherAsyncTask getAsyncImageTask(ImageSwitcher imageSwitcher) {
        if (imageSwitcher != null) {
            Object tag = imageSwitcher.getTag();
            if (tag != null && tag instanceof LocalImageSwitcherAsyncTask)
                return (LocalImageSwitcherAsyncTask) tag;
        } 
        return null; 
    } 
 
    /** 
     * 异步本地加载图片(用于ImageSwitcher) 
     */ 
    protected class LocalImageSwitcherAsyncTask extends AsyncTask<Void, Void, Bitmap> {
        private Context context;
        private final WeakReference<ImageSwitcher> switcherReference;
        private String imageUrl;
        private XImageProcessor.ImageSize size;// 加载的图片尺寸
        private boolean invalidate;// 标识是否AysncTask自身是否无效
 
        public LocalImageSwitcherAsyncTask(Context context, ImageSwitcher switcher, String imageUrl,
                                           XImageProcessor.ImageSize size) {
            // Use a WeakReference to ensure the ImageView can be garbage collected 
            this.context = context;
            this.switcherReference = new WeakReference<ImageSwitcher>(switcher);
            this.imageUrl = imageUrl;
            this.size = size;
            invalidate = false;
        } 
 
        public String getImageUrl() {
            return imageUrl;
        } 
 
        public void setInvalidate() { 
            invalidate = true;
        } 
 
        // Decode image in background. 
        @Override 
        protected Bitmap doInBackground(Void... params) {
            if (invalidate)
                return null; 
 
            // 保持上次的bitmap不被销毁 
            addLastBitmap(size);
            // 加载真正的图片 
            Bitmap bitmap = loadRealImage(context, imageUrl, size);
            return bitmap;
        } 
 
        // Once complete, see if ImageView is still around and set bitmap. 
        @Override 
        protected void onPostExecute(Bitmap bitmap) {
            if (isCancelled())
                bitmap = null;
 
            if (switcherReference != null && bitmap != null && !bitmap.isRecycled()) {
                // 记录当前bitmap为LastBitmap 
                mPreBitmap = mNextBitmap;
                mNextBitmap = bitmap;
                // 设置图片 
                final ImageSwitcher switcher = switcherReference.get();
                final LocalImageSwitcherAsyncTask asyncImageTask = getAsyncImageTask(switcher);
                if (this == asyncImageTask && switcher != null && !invalidate) {
                    switcher.setImageDrawable(new BitmapDrawable(bitmap));
                    switcher.setTag(null);
                } 
            } 
        } 
    } 
}