第三人称模仿者 2014-12-24 08:23 采纳率: 0%
浏览 2358

很棘手的问题,关于gridview加载图片

  • 1. * 我的问题是用画布标记已经选中的图片,选中之后如果不重用view被选中的状态划过去再划过来是存在的,如果重用的话就会内存溢出,下面是我的代码,请哪位大帮忙看一看。
package com.yonyou.uap.um.control.image;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Build;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.yonyou.uap.um.animation.UMAnimatorUpdateListener;
import com.yonyou.uap.um.base.UMAttributeHelper;
import com.yonyou.uap.um.control.ImageSelector;
import com.yonyou.uap.um.core.UMActivity;
import com.yonyou.uap.um.util.BitmapUtil;

public class ImageSelectorAdapter extends BaseAdapter {

    private static final String TAG = ImageSelectorAdapter.class.getName();
    public static final float SCALE = 0.92f;
    private List<ImageItem> mImages = null;
    private Context mContext = null;

    private static Bitmap select_icon = null;
    private static Paint select_paint = null;

    private ImageSelector mControl = null;

    static {
        select_icon = Bitmap.createScaledBitmap(
                BitmapUtil.getBitmapFromSrc("", "icon_data_select.png"),
                UMAttributeHelper.getSize(30 + ""),
                UMAttributeHelper.getSize(30 + ""), true);
        select_paint = new Paint();
        select_paint.setColor(Color.RED);
        select_paint.setStyle(Paint.Style.STROKE);
        select_paint.setStrokeWidth(4);
    }

    public ImageSelectorAdapter(Context ctx, ImageSelector control,
            List<ImageItem> images) {
        if (ctx == null) {
            throw new Error("ctx is null");
        }
        mControl = control;
        mImages = images;
        if (mImages == null) {
            mImages = new ArrayList<ImageItem>();
        }
        mContext = ctx;
    }

    @Override
    public int getCount() {
        int count = 0;
        if (mImages != null) {
            count = mImages.size();
        }
        return count;
    }

    @Override
    public Object getItem(int position) {
        return mImages.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    private Set<Integer> selectedItems = new HashSet<Integer>();
    private HashMap<Integer, ImageViewItem> mCache = new HashMap<Integer, ImageViewItem>();

    @SuppressLint("NewApi")
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageViewItem rs = null;
        if (mCache.containsKey(position)) {
            rs = mCache.get(position);
        } else {
            rs = this.new ImageViewItem(mContext);
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
                rs.setId(View.generateViewId());
            } else {
                rs.setId(100000 + position);
            }
            rs.setImageBitmap(BitmapUtil.loadIdImage(
                    "friends_sends_pictures_no", mContext));
            final ImageItem item = (ImageItem) getItem(position);
            rs.loadImageFromPath(item.getImagePath());
            rs.setOnClickListener(new ImageViewItemClick(position));

            AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    mControl.getRowHeight());
            rs.setLayoutParams(lp);

//          rs.setOnLongClickListener(new View.OnLongClickListener() {
//              
//              @Override
//              public boolean onLongClick(View v) {
//                  mControl.showImageView(item.getImagePath());
//                  return true;
//              }
//          });
            mCache.put(position, rs);
        }

        return rs;
    }

    @SuppressLint("NewApi")
    private View convertTest(int position, View convertView) {
        ImageViewItem rs = null;
        if (convertView == null) {
            rs = this.new ImageViewItem(mContext);
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
                rs.setId(View.generateViewId());
            } else {
                rs.setId(100000 + position);
            }
        } else {
            rs = (ImageViewItem) convertView;
        }
        rs.setImageBitmap(BitmapUtil.loadIdImage("friends_sends_pictures_no",
                mContext));
        ImageItem item = (ImageItem) getItem(position);
        rs.loadImageFromPath(item.getImagePath());

        rs.setOnClickListener(new ImageViewItemClick(position));

        AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, mControl.getRowHeight());
        rs.setLayoutParams(lp);

        return rs;
    }

    private class ImageViewLoader implements Runnable {

        private String path = "";
        private ImageViewItem item = null;
        private Bitmap bitmap = null;

        public ImageViewLoader(ImageViewItem rs, String p) {
            // rs.beginLoad();
            item = rs;
            path = p;
        }

        @Override
        public void run() {
            long start = System.currentTimeMillis();
            BitmapFactory.Options options = new BitmapFactory.Options();
            // 设置为true,表示解析Bitmap对象,该对象不占内存
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, options);
            // 设置缩放比例
            options.inSampleSize = computeScale(options, 300, 200);

            // 设置为false,解析Bitmap对象加入到内存中
            options.inJustDecodeBounds = false;
            bitmap = BitmapFactory.decodeFile(path, options);

            Log.d(ImageSelectorAdapter.TAG,
                    "load image  - " + (System.currentTimeMillis() - start));
            Activity ctx = (Activity) ImageSelectorAdapter.this.mContext;
            // if (Thread.interrupted()) {
            // return;
            // }
            ctx.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    item.setImageBitmap(bitmap);
                    item.setTag(bitmap);
                }
            });

        }

    }

    /**
     * 根据View(主要是ImageView)的宽和高来计算Bitmap缩放比例。默认不缩放
     * 
     * @param options
     * @param width
     * @param height
     */
    private int computeScale(BitmapFactory.Options options, int viewWidth,
            int viewHeight) {
        int inSampleSize = 1;
        if (viewWidth == 0 || viewWidth == 0) {
            return inSampleSize;
        }
        int bitmapWidth = options.outWidth;
        int bitmapHeight = options.outHeight;

        // 假如Bitmap的宽度或高度大于我们设定图片的View的宽高,则计算缩放比例
        if (bitmapWidth > viewWidth || bitmapHeight > viewWidth) {
            int widthScale = Math
                    .round((float) bitmapWidth / (float) viewWidth);
            int heightScale = Math.round((float) bitmapHeight
                    / (float) viewWidth);

            // 为了保证图片不缩放变形,我们取宽高比例最小的那个
            inSampleSize = widthScale < heightScale ? widthScale : heightScale;
        }
        return inSampleSize;
    }

    private class ImageViewItemClick implements View.OnClickListener {

        private int mPosition = 0;

        public ImageViewItemClick(int position) {
            mPosition = position;
        }

        @Override
        public void onClick(View v) {
            ImageViewItem item = (ImageViewItem) v;
            item._switch();
            if (item.isSelected()) {
                ImageSelectorAdapter.this.selectedItems.add(mPosition);
                item.setAlpha(100);
            } else {
                if (ImageSelectorAdapter.this.selectedItems.contains(mPosition)) {
                    ImageSelectorAdapter.this.selectedItems.remove(mPosition);
                    item.setAlpha(255);
                }
            }
            Log.e("PATH", "路径:" + mImages.get(mPosition).imagePath);
        }

    }

    private class ImageViewItem extends ImageView {

        public ImageViewItem(Context context) {
            super(context);
            this.setScaleType(ScaleType.CENTER_CROP);
        }

        private Thread loader = null;

        private boolean mIsSelectedItem = false;

        public synchronized void loadImageFromPath(String path) {
            loader = new Thread(new ImageViewLoader(this, path));
            loader.start();
        }

        public boolean isSelectedItem() {
            return mIsSelectedItem;
        }

        public void setSelectedItem(boolean value) {
            this.mIsSelectedItem = value;
        }

        private void _switch() {
            this.setSelectedItem(!this.isSelectedItem());
            this.invalidate();
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                this.setScaleX(ImageSelectorAdapter.SCALE);
                this.setScaleY(ImageSelectorAdapter.SCALE);
                break;
            case MotionEvent.ACTION_UP:
                resetScale();
                break;
            case MotionEvent.ACTION_CANCEL:
                resetScale();
                break;
            default:
                break;
            }
            return super.onTouchEvent(event);
        }

        private void resetScale() {
            this.setScaleX(1f);
            this.setScaleY(1f);
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int width = MeasureSpec.getSize(widthMeasureSpec);
            setMeasuredDimension(width, width);
        }

        // public void _switch(boolean value) {
        // setImageItemSelected(value);
        // Log.e(ImageSelectorAdapter.TAG, "  switch to(" + this.getId()
        // + ") - " + value);
        // this.invalidate();
        // }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            Log.e(ImageSelectorAdapter.TAG, "   onDraw(" + this.getId()
                    + ") - " + this.isSelected());
            if (this.isSelectedItem()) {
                Rect rect = canvas.getClipBounds();
                canvas.drawRect(rect, select_paint);
                canvas.drawBitmap(select_icon, 60, 10, select_paint);

            }
        }
    }

}

尝试过很多结局办法了,还有一种情况会发生,就是内存不溢出状态也在,就是有时候有的图片点击事件不起作用,滑动,被点击的图片才会被标记上。

  • 写回答

1条回答 默认 最新

  • danielinbiti 2014-12-24 10:07
    关注

    描述不是很清楚,最好加张图。贴个错误

    评论

报告相同问题?

悬赏问题

  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站