从网格视图加载图像并滑动从parse.com调用的所有图像

时间:2014-07-27 04:54:06

标签: android gridview parse-platform gallery swipe

所以我在parse.com的网格视图中成功加载图像,但是我将图像传递给我的ImageDetail类时遇到了麻烦,而且我还试图在ViewPager中加载图像以便我可以滑动根据发送图像的位置,图库中的图像..

以下是一些供参考的代码,我将非常感谢任何帮助或建议,以帮助我更接近我想要实现的目标。

这是我的Gallery的适配器:

public class GalleryAdapter extends BaseAdapter {

    Context context;
    LayoutInflater inflate;
    LoadImages loadImages;
    public static List<MyImages> galleryImages;
    private ArrayList<MyImages> imageUrls;


    public GalleryAdapter(Context context, List<MyImages> galleryImages){
        this.context = context;
        this.galleryImages = galleryImages;
        inflate = LayoutInflater.from(context);
        this.imageUrls = new ArrayList<MyImages>();
        this.imageUrls.addAll(galleryImages);

        loadImages = new LoadImages(context);

    }

    public class ViewHolder {
        ImageView picture;
    }

    @Override
    public int getCount() {
        return galleryImages.size();
    }

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

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


    @Override
    public View getView(final int position, View view, ViewGroup parent) {
        // TODO Auto-generated method stub
        final ViewHolder holder;
        if (view == null){
            holder = new ViewHolder();
            view = inflate.inflate(R.layout.gallery_image, null);
            // find image in gallery_image
            holder.picture = (ImageView) view.findViewById(R.id.picture);
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }

        // load into myGallery gridview
        loadImages.DisplayImages(galleryImages.get(position).getImages(), holder.picture);
        GalleriesFragment.myGallery.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // TODO pass position of image to ImageDetail view

                Intent viewPic = new Intent(context, ImageDetail.class);

                // pass data
                viewPic.putExtra("pic", galleryImages.get(position).getImages());

                Bundle bundle = new Bundle();
                bundle.putInt("position", position);

                //viewPic.putExtra("position", galleryImages.get(position));

                //ImageDetail.pager.setCurrentItem(galleryImages.get(position));

                context.startActivity(viewPic);
            }


        });

        return view;
    }


}

这里是ImageDetail类,我试图在从图库中点击的图片中调用,然后根据所选图像的位置扫描上一张/下一张图像:

public class ImageDetail extends Activity {

    private ViewPager pager;
    public static String pic;
    LoadImages loading = new LoadImages(this);
    ImageView selectedImage;
    ImageView exitToGallery;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_detail);

        // get intent from GalleriesFragment - get selected image
        Intent getPic = getIntent();
        // get image
        // pic = getPic.getExtras().getString("pic");
        pic = getPic.getStringExtra("pic");

        Bundle getBundle = getPic.getExtras();
        position = getBundle.getInt("position");

        // position = getPic.getExtra("position");

        pager = (ViewPager) findViewById(R.id.pager);
        SwipeImageAdapter swipeAdapter = new SwipeImageAdapter();
        pager.setAdapter(swipeAdapter);
        pager.setCurrentItem(position);

        Toast.makeText(MainActivity.context,
                "Simply hit the back key to return to Galleries.",
                Toast.LENGTH_LONG).show();

    }

    // for closing the view
    @Override
    public void finish() {

        super.finish();
    }

    // Class for Swipe Image Functionality using ViewPager
    private class SwipeImageAdapter extends PagerAdapter {

        public int getCount() {

            // TODO Auto-generated method stub
            return GalleryAdapter.imageUrls.size();

        }

        /*
         * // can't seem to get correct position of image tapped public String
         * getItem(int position) { // TODO Auto-generated method stub
         * 
         * //return GalleryAdapter.getImageurls().get(position); return
         * GalleriesFragment.galleryImages.get(position).toString();
         * 
         * }
         * 
         * public long getItemId(int position) { // TODO Auto-generated method
         * stub
         * 
         * return position;
         * 
         * }
         */

        @Override
        public boolean isViewFromObject(View view, Object obj) {
            // TODO Auto-generated method stub
            return view == ((ImageView) obj);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Context context = ImageDetail.this;

            selectedImage = new ImageView(context);
            exitToGallery = new ImageView(context);
            exitToGallery.setImageResource(R.drawable.close);

            LinearLayout.LayoutParams layout = new LinearLayout.LayoutParams(
                    300, 500);
            selectedImage.setLayoutParams(layout);
            // pager.getCurrentItem();

            // loading.DisplayImages(GalleryAdapter.imageUrls.indexOf(position),
            // selectedImage);

            loading.DisplayImages(pic, selectedImage);
            // selectedImage.setImageResource(GalleryAdapter.imageUrls.indexOf(getBundle));
            // using below stretches images, but otherwise they show up tiny on the image detail page =(
            selectedImage.setScaleType(ImageView.ScaleType.FIT_XY);

            // selectedImage.setScaleType(ImageView.ScaleType.CENTER_INSIDE);

            exitToGallery.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO return to Galleries
                    finish();

                }

            });

            ((ViewPager) container).addView(selectedImage, 0);
            ((ViewPager) container).addView(exitToGallery, 0);

            return selectedImage;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object obj) {
            ((ViewPager) container).removeView((ImageView) obj);
        }

    }
}

- 我也试过将从意图传递的图像加载到ImageDetail活动的图像视图中,但我无法显示图像。

我有更多的类/代码可供参考,与parse.com调用我的图片有关,但我认为我现在所分享的内容可能足以支持上下文。

已修改为包含加载图片的课程

public class LoadImages {

    CacheMemory cacheMem = new CacheMemory();
    CacheFile cacheFile;
    private Map<ImageView, String> myPictures = Collections.synchronizedMap(new WeakHashMap<ImageView, String>());

    ExecutorService executeService;
    // this will display images to UI
    Handler handleImages = new Handler();

    public LoadImages(Context context){
        cacheFile = new CacheFile(context);
        executeService = Executors.newFixedThreadPool(5);
    }

    final int placeholder = R.drawable.famous;

    public void DisplayImages(String url, ImageView pic){
        myPictures.put(pic, url);
        Bitmap bitmap = cacheMem.get(url);
        if (bitmap != null){
            pic.setImageBitmap(bitmap);
        } else {
            queuePic(url, pic);
            pic.setImageResource(placeholder);
        }
    }

    private void queuePic(String url, ImageView pic){
        PicToLoad loadPic = new PicToLoad(url, pic);
        executeService.submit(new PicLoader(loadPic));
    }

    private Bitmap getBitmap(String url){
        File file = cacheFile.getFile(url);
        Bitmap newBitmap = decode(file);
        if (newBitmap != null){
            return newBitmap;
        }

        // download my gallery images from parse.com
        try {
            Bitmap bitmap = null;
            URL imgUrl = new URL(url);
            HttpURLConnection connect = (HttpURLConnection) imgUrl.openConnection();
            connect.setConnectTimeout(20000);
            connect.setReadTimeout(20000);
            connect.setInstanceFollowRedirects(true);

            InputStream input = connect.getInputStream();
            OutputStream output = new FileOutputStream(file);
            Utilities.copy(input, output);
            output.close();
            connect.disconnect();
            bitmap = decode(file);
            return bitmap;
        } catch (Throwable exception){
            exception.printStackTrace();
            if (exception instanceof OutOfMemoryError)
                cacheMem.clear();
            return null;
        }
    }

    // decode image, scale to reduce memory usage
    private Bitmap decode(File file) {
        try{
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            FileInputStream stream = new FileInputStream(file);
            BitmapFactory.decodeStream(stream, null, options);
            stream.close();

            final int desiredImgSize = 150;
            int width = options.outWidth, height = options.outHeight;
            int scale = 1;
            while (true){
                if (width / 2 < desiredImgSize || height / 2 < desiredImgSize)
                    break;
                    width /= 2;
                    height /= 2;
                    scale *= 2;

            }

            BitmapFactory.Options options2 = new BitmapFactory.Options();
            options2.inSampleSize = scale;
            FileInputStream stream2 = new FileInputStream(file);
            Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, options2);
            stream2.close();
            return bitmap;
        } catch (FileNotFoundException e){

        } catch (IOException e){
            e.printStackTrace();
        }

        return null;
    }

    // for queue
    private class PicToLoad {
        public String url;
        public ImageView pic;

        public PicToLoad(String url2, ImageView pic2){
            url = url2;
            pic = pic2;
        }
    }

    class PicLoader implements Runnable {
        PicToLoad picToLoad;

        PicLoader(PicToLoad picToLoad) {
            this.picToLoad = picToLoad;
        }

        @Override
        public void run() {
            // TODO Auto-generated method stub
            try {
                if (recycleImageView(picToLoad))
                    return;
                Bitmap bit = getBitmap(picToLoad.url);
                cacheMem.put(picToLoad.url, bit);
                if (recycleImageView(picToLoad))
                    return;
                DisplayBitmap display = new DisplayBitmap(bit, picToLoad);
                handleImages.post(display);
            } catch (Throwable e){
                e.printStackTrace();
            }
        }   

    }

     boolean recycleImageView(PicToLoad picToLoad) {
            String tag = myPictures.get(picToLoad.pic);
            if (tag == null || !tag.equals(picToLoad.url))
                return true;
            return false;
        }

    // display Bitmap on UI
    class DisplayBitmap implements Runnable {
        Bitmap bitmap;
        PicToLoad picToLoad;

        public DisplayBitmap(Bitmap bm, PicToLoad pl){
            bitmap = bm;
            picToLoad = pl;
        }

        @Override
        public void run() {
            // TODO Auto-generated method stub
            if (recycleImageView(picToLoad))
                return;
            if (bitmap != null){
                picToLoad.pic.setImageBitmap(bitmap);
            } else {
                picToLoad.pic.setImageResource(placeholder);
            }

        }
    }

    public void clearCache(){
        cacheMem.clear();
        cacheFile.clear();
    }

}

2 个答案:

答案 0 :(得分:0)

ViewPager的getCount方法返回零,它应该返回arraylist中的条目数,即arraylist.size()

答案 1 :(得分:0)

因此,对于任何可能遇到与我相同问题的人,我都能让它发挥作用!

当我传递图像时:

GalleriesFragment.myGallery.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // TODO pass position of image to ImageDetail view

            Intent viewPic = new Intent(context, ImageDetail.class);

            // pass data
            viewPic.putExtra("pic", galleryImages.get(position).getImages());
            // pass position
            viewPic.putExtra("id", position);

            context.startActivity(viewPic);
        }


    });

如何接收它:

public class ImageDetail extends Activity {
    // changed from private to public static
    public static ViewPager pager;
    public static String pic;
    public static int position;
    LoadImages loading = new LoadImages(this);
    ImageView selectedImage;
    ImageView exitToGallery;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_detail);

        // get intent from GalleriesFragment - get selected image
        Intent getPic = getIntent();
        // get image
        pic = getPic.getStringExtra("pic");
        // get position to open image tapped and display in the pager
        position = getPic.getExtras().getInt("id");

        Log.d("position = ", +position+"");

        pager = (ViewPager) findViewById(R.id.pager);
        SwipeImageAdapter swipeAdapter = new SwipeImageAdapter();
        pager.setAdapter(swipeAdapter);
        pager.setCurrentItem(position);


        Toast.makeText(MainActivity.context,
                "Simply hit the back key to return to Galleries.",
                Toast.LENGTH_LONG).show();

    }

    // for closing the view
    @Override
    public void finish() {

        super.finish();
    }

    // Class for Swipe Image Functionality using ViewPager
    private class SwipeImageAdapter extends PagerAdapter {

        public int getCount() {

            // TODO Auto-generated method stub
            return GalleryAdapter.imageUrls.size();

        }

        Object getItem(int position){

            return position;
        }


        @Override
        public boolean isViewFromObject(View view, Object obj) {
            // TODO Auto-generated method stub
            return view == ((ImageView) obj);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Context context = ImageDetail.this;

            selectedImage = new ImageView(context);
            exitToGallery = new ImageView(context);
            exitToGallery.setImageResource(R.drawable.close);

            LinearLayout.LayoutParams layout = new LinearLayout.LayoutParams(
                    300, 500);
            selectedImage.setLayoutParams(layout);

            String img = GalleryAdapter.galleryImages.get(position).getImages();

            loading.DisplayImages(img, selectedImage);

            selectedImage.setScaleType(ImageView.ScaleType.CENTER_INSIDE);

            exitToGallery.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO return to Galleries
                    finish();

                }

            });

            ((ViewPager) container).addView(selectedImage, 0);
            ((ViewPager) container).addView(exitToGallery, 0);

            return selectedImage;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object obj) {
            ((ViewPager) container).removeView((ImageView) obj);
        }

    }
}