Swiping images (not layouts) with viewpager

后端 未结 2 1131
自闭症患者
自闭症患者 2021-01-01 05:30

What my code does:

Here\'s my code which for viewpager that swipes between xml layouts (named left.xml, right.xml and center.xml).

W

相关标签:
2条回答
  • 2021-01-01 06:05

    I think one option would be to insert each image into its own layout with an ImageView and then inflate the layout that the image is in rather than the image itself.

    0 讨论(0)
  • 2021-01-01 06:12

    If you are using the same implementation and just adding R.drawable.XXX instead of R.layout.YYY then the problem is right there. You are using LayoutInflater to inflate ImageViews, the layout inflater as it states by itself it inflates a whole layout in a single View.

    Instead of doing that try to create ImageView objects through code and then in the return return the newly created ImageView. Some sample code would be:

    public Object instantiateItem(View collection, int position) {
    
        ImageView img = new ImageView(context); //this is a variable that stores the context of the activity
        //set properties for the image like width, height, gravity etc...
    
        int resId = 0;
        switch (position) {
            case 0:
                resId = R.drawable.img1;
                break;
            case 1:
                resId = R.drawable.img2;
                break;
            case 2:
                resId = R.drawable.img3;
                break;
        }
    
        img.setImageResource(resId); //setting the source of the image
        return img;
    }
    

    If you are just using a specific amount of images or pages you should consider adding them in the xml that contains the ViewPager rather than dynamically creating the ViewPager.

    0 讨论(0)
提交回复
热议问题