How to swipe images

前端 未结 7 1178
孤城傲影
孤城傲影 2021-02-05 14:34

I am trying to implement a simple gallery of images in which I have an image to be displayed at a time on the device screen. When we swipe the screen from left to right it shoul

7条回答
  •  粉色の甜心
    2021-02-05 15:27

    You can create a custom Pager Adapter for your ViewPager:

    public class ImageAdapter extends PagerAdapter {
        private Context context;
        private int[] GalImages = new int[]{
                R.drawable.cap8, R.drawable.cap2, R.drawable.cap3, R.drawable.cap1, R.drawable.cap5,
                R.drawable.cap6, R.drawable.cap7, R.drawable.cap9, R.drawable.cap4,
                R.drawable.cap10
    
        };
    
        ImageAdapter(Context context) {
            this.context = context;
        }
    
        @Override
        public int getCount() {
            return GalImages.length;
        }
    
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ImageView imageView = new ImageView(context);
            int padding = context.getResources().getDimensionPixelSize(R.dimen.activity_horizontal_margin);
            imageView.setPadding(padding, padding, padding, padding);
            imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
            imageView.setImageResource(GalImages[position]);
            container.addView(imageView, 0);
            return imageView;
        }
    
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((ImageView) object);
        }
    }
    

    Use the ViewPager in your layout and register the adapter:

    
    

提交回复
热议问题