Android Fragment vertical and horizontal infinite loop sliding

In recent projects, the Fragment can slide in an endless loop both horizontally and vertically, and finally realized after some tossing.

// It must be ensured that there are 4 fragments when adding. No 4 fragments will be abnormal.

 First of all, the infinite loop is the same as most methods on the Internet, and the getCount() in the PagerAdapter returns the largest number. Integer.MAX_VALUE

 

 @Override
    public int getCount() {
        return Integer.MAX_VALUE; // fragments.size();
    }

 

Do not return the destroyItem of the parent class in destroyItem(), the following code:

@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
		android.util.Log.d(TAG, " destroyItem " + position);
		int pos = position % fragments.size();
		container.removeView((View) object);
		// super.destroyItem(container, position, object);
	}

In instantiateItem(), in order to prevent repeated destruction and creation when sliding the Fragment, first determine whether to add, and return the added ones directly

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
    	int pos = position % fragments.size();
        Fragment fragment = fragments.get(pos);
        
        android.util.Log.d(TAG, " instantiateItem " + pos);
        
        if(!fragment.isAdded()) {
            FragmentTransaction ft = fragmentManager.beginTransaction();
            ft.add(fragment, fragment.getClass().getSimpleName());
            ft.commit();
            fragmentManager.executePendingTransactions();
        }

        if(fragment.getView().getParent() == null) container.addView(fragment.getView()); // 为viewpager增加布局
        return fragment.getView();
    }

 

Customized a HorizontalViewPager and VerticalViewPager.

Effect picture:

 

Fragment of horizontal and vertical switching

 

 

Code download

Guess you like

Origin blog.csdn.net/u011694328/article/details/108885620