H
H
Horoko2015-08-03 14:37:14
Java
Horoko, 2015-08-03 14:37:14

How to change content of ImageView in ViewPager Android?

Adapter code

public class ContactPagerAdapter extends PagerAdapter {

        public ContactPagerAdapter() {
            super();
        }

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

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
         
            pos = position;
            if (uris.size()!=0){
               photoImage = new ImageView(getApplicationContext());
                photoImage.setScaleType(ImageView.ScaleType.CENTER_CROP);
                photoImage.setImageURI(uris.get(position));
   
            container.addView(photoImage, 0);
            photoImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

            }
            });}
            return photoImage;
        }


        @Override
        public void destroyItem(ViewGroup container, int position, Object view) {
            container.removeView((View) view);
        }

        @Override
        public boolean isViewFromObject(View v, Object o) {
            return v == ((View) o);
        }
    }

And the method that photo changes
public static void changePhoto(int id) {
         photoImage.setImageURI(uris.get(id));
        adapter.notifyDataSetChanged();

Only the first and last element can be changed in ViewPager in this way.
Subject. How to change any element, namely ImageView, not just the last and first.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
Oleg Gamega, 2015-08-03
@Horoko

if I understand correctly, your uris is a collection that stores the uri of images
, just change the value of the element you need of this collection
, you don’t need to try to change the image with your hands, this will happen at the time of redrawing when you call
notifyDataSetChanged PS
use something for asynchronous loading, for example picasso, otherwise it will be to brake

H
Horoko, 2015-08-03
@Horoko

Thanks for the answers, I decided that in my task it would be easier to change the viewpage of the ViewPager using the setCurrentItem() method than to try to change the content with crutches in order to achieve the same result as this method provides. One question on the Picasso library, when calling Picasso.with(getAplicationContext).load(uris.get(position)).into(photoImage); it doesn't output anything to the ImageView. Why? wrong context?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question