Can I use view pager with views (not with fragments)

前端 未结 7 1942
情深已故
情深已故 2020-11-28 01:39

I am using ViewPager for swiping between Fragments, but can I use ViewPager to swipe between Views simple XML layout?

相关标签:
7条回答
  • 2020-11-28 02:35

    We have build a very simple subclass of the ViewPager that we use sometimes.

    /**
     * View pager used for a finite, low number of pages, where there is no need for
     * optimization.
     */
    public class StaticViewPager extends ViewPager {
    
        /**
         * Initialize the view.
         *
         * @param context
         *            The application context.
         */
        public StaticViewPager(final Context context) {
            super(context);
        }
    
        /**
         * Initialize the view.
         *
         * @param context
         *            The application context.
         * @param attrs
         *            The requested attributes.
         */
        public StaticViewPager(final Context context, final AttributeSet attrs) {
            super(context, attrs);
        }
    
        @Override
        protected void onAttachedToWindow() {
            super.onAttachedToWindow();
    
            // Make sure all are loaded at once
            final int childrenCount = getChildCount();
            setOffscreenPageLimit(childrenCount - 1);
    
            // Attach the adapter
            setAdapter(new PagerAdapter() {
    
                @Override
                public Object instantiateItem(final ViewGroup container, final int position) {
                    return container.getChildAt(position);
                }
    
                @Override
                public boolean isViewFromObject(final View arg0, final Object arg1) {
                    return arg0 == arg1;
    
                }
    
                @Override
                public int getCount() {
                    return childrenCount;
                }
    
                @Override
                public void destroyItem(final View container, final int position, final Object object) {}
            });
        }
    
    }
    

    This class does not need a adapter as it will load the views from the layout. In order to use it your projects, just use it instead of the android.support.v4.view.ViewPager.

    All the fancy stuff will still work, but you do not need to be bothered with the adapters.

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