Search code examples
androidandroid-viewpagerscaletype

How to set android:scaleType to a viewPager


I want to set android:scaleType attribute to a viewpager to scale the images of a viewpager. But i cannot find the attribute within ViewPager. Is there any other similar attribute which I can use. I even tried a third party viewpager, but didnt work. Pls help and thanks in advance.


Solution

  • Leave your ViewPager as is. Build a custom adapter (extending PagerAdapter) for your ViewPager, where you inflate a certain view for every position. This certain view will hold an ImageView, and you'll pass your image to this ImageView in the adapter's following method:

    @Override
    public View instantiateItem(ViewGroup container, int position) {
        View view = mInflater.inflate(R.layout.pager_item_with_image, container, false);
        ((ImageView) view.findViewById(R.id.my_image_view)).setImageResource(mImages[position]);
    
        container.addView(view, 0);
        return view;
    }
    

    And this might be your adapter's constructor with the needed variables:

    LayoutInflater mInflater;
    private static final int[] mImages;
    static {
        mImages = new int[]{
                R.drawable.img1,
                R.drawable.img2,
                R.drawable.img3,
                R.drawable.img4,
                R.drawable.img5,
        };
    }
    
    public MyViewPagerAdapter(Context context) {
        mInflater = LayoutInflater.from(context);
    }