将Picasso库与ImageSwitcher一起使用会导致Object出现内存错误

时间:2014-06-12 17:37:33

标签: android picasso imageswitcher

我想在我的Image Switcher中有效地加载大位图,我一直在使用Picasso来实现这个目的,但现在我陷入了困境。如果没有Picasso很多OOMs以及其他令人讨厌的异常,请告诉我是否可以将此库与Image Switcher一起使用。 如果是,则提供示例代码。

谢谢!

imswitch.setFactory(new ViewFactory() {

        @Override
        public View makeView() {
              ImageView imageView = new ImageView(getApplicationContext());
              imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
              imageView.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
              return imageView;
        }
    } );

并点击:

     btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
               currentIndex++;
               // If index reaches maximum reset it
                if(currentIndex==messageCount)
                    currentIndex=0;
                ImageView imageView = (ImageView)findViewById(R.id.imswitch);
                Picasso.with(getApplicationContext()).load(imageIds[currentIndex]).into(imageView);
                Toast.makeText(getApplicationContext(), "Pressed "+currentIndex,Toast.LENGTH_LONG).show();
        }

1 个答案:

答案 0 :(得分:4)

其中一种可能的方法是使用Target接口创建自己的实现。

https://square.github.io/picasso/javadoc/com/squareup/picasso/Target.html

public class ImageSwitcherPicasso implements Target {

        private ImageSwitcher mImageSwitcher;
        private Context mContext;

        public ImageSwitcherPicasso(Context context, ImageSwitcher imageSwitcher){
            mImageSwitcher = imageSwitcher;
            mContext = context;
        }

        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom loadedFrom) {
            mImageSwitcher.setImageDrawable(new BitmapDrawable(mContext.getResources(), bitmap));
        }

        @Override
        public void onBitmapFailed(Drawable drawable) {

        }

        @Override
        public void onPrepareLoad(Drawable drawable) {

        }

    }

不只是使用如下



    ImageSwitcherPicasso mImageSwitcherPicasso = new ImageSwitcherPicasso(getActivity(), playerBackground);
    Picasso.with(getActivity()).load(new File(path)).into(mImageSwitcherPicasso);


其中playerBackground是对ImageSwitcher的引用