Search code examples
android-viewpagerimage-scaling

Android: Unwanted Image stretching in ViewPager


After several failed attempts of implementing a simple sliding image gallery, I have finally implemented something that works close to the way I want it, following this tutorial: http://androidtrainningcenter.blogspot.dk/2012/10/viewpager-example-in-android.html

However, my images in the ImageViews, in the ViewPager, are stretched to the corners of the screen, and I simply cannot find out how to fix it. I have adjusted every march_parent and wrap_content that I could possibly find, but nothing makes even the slightest difference.

I suspected that this method might be the right to edit:

public Object instantiateItem(View collection, int position) {
    ImageView view = new ImageView(activity);
    view.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.MATCH_PARENT));
    view.setScaleType(ScaleType.CENTER_INSIDE);
    view.setBackgroundResource(imageArray[position]);
    ((ViewPager) collection).addView(view, 0);
    return view;
}

I have played with the .setScaleType-method, but whatever i set it to, it makes no difference whatsoever. The rest of my code is directly copied from the linked tutorial, except from the specific drawable resources.


Solution

  • Yes, it is the right place to edit, you need to use view.setImageResource() rather than setBackgroundResource().

    The same thing happened with me, the properties you are setting is not getting applied if its a background I suspect. Lemme know if this works for you.

    @Override
    public Object instantiateItem(View container, int position) {
        ImageView view = new ImageView(activity);
        view.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
        view.setAdjustViewBounds(true);
        view.setScaleType(ScaleType.FIT_CENTER);
        view.setImageResource(imageArray[position]);
        ((ViewPager) container).addView(view, 0);
        return view;
    }