【问题标题】:Load image from grid view and swipe through all images called from parse.com从网格视图加载图像并浏览从 parse.com 调用的所有图像
【发布时间】:2014-09-18 15:00:12
【问题描述】:

所以我成功地从 parse.com 在我的网格视图中加载图像,但是我无法将图像传递给我的 ImageDetail 类,而且我试图在 ViewPager 中加载图像,以便我可以滑动浏览画廊中的图像基于发送图像的位置..

这里有一些代码供参考,如果有任何帮助或建议可以帮助我更接近我想要实现的目标,我将不胜感激。

这是我的画廊适配器:

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);
        }

    }
}

-- 我也尝试将 Intent 传递的图像加载到 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();
    }

}

【问题讨论】:

    标签: android gridview parse-platform gallery swipe


    【解决方案1】:

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

    【讨论】:

    • 谢谢,我确实解决了这个问题,但它仍然只加载我选择的图像并一次又一次地在同一个图像上滑动。我认为这与我必须加载图像的类有关 loading.DisplayImages(pic, selectedImage);我试图在我的视图寻呼机中设置图像的当前位置,但上述方法会覆盖它。我找不到如何解决这个问题,因为它需要一个字符串元素(在这种情况下是我的“图片”)并且不会接受位置(int)pager.setCurrentItem(位置);
    • 编辑了我的问题以包含更新的代码。感谢您为解决此问题提供的任何帮助,这让我发疯了 :) 大声笑
    【解决方案2】:

    因此,对于可能遇到与我相同问题的任何人,我都成功了!

    当我传递图像时:

    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);
            }
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-05-14
      • 2019-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多