Android: how to use ViewPage

catalog

1. Definition

  • ViewPager is a class in the Android extension package v4 package
android.support.v4.view.ViewPager
  • Similar to LinearLayout, the ViewPager class directly inherits the ViewGroup class and is a container in which we need to add the content we want to display.
  • Similar to ListView, the ViewPager class requires the pagertadapter adapter class to provide data.

2. Function

  • Switch the current view left and right to achieve the effect of sliding switch.

3. Use

To create a ViewPage:

  1. Add to XML layout android.support.v4.view.ViewPager :
     <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />
  1. Load the page card to be displayed in MainActivity:

When the page card to be loaded is View:

 LayoutInflater lf = getLayoutInflater().from(this);
        view1 = lf.inflate(R.layout.layout1, null);
        view2 = lf.inflate(R.layout.layout2, null);
        view3 = lf.inflate(R.layout.layout3, null);

        viewList = new ArrayList<View>();// Load the View to be paged into the array
        viewList.add(view1);
        viewList.add(view2);
        viewList.add(view3);

When the page card to be loaded is Fragment:

        
        Fragment1 fragment1 = new Fragment1();
        Fragment2 fragment2 = new Fragment2();
        Fragment3 fragment3 = new Fragment3();
        Fragment4 fragment4 = new Fragment4();

      // Load the View to be displayed in pages into the array
      List<Fragment> list = new ArrayList<Fragment>();
        list.add(fragment1);
        list.add(fragment2);
        list.add(fragment3);
        list.add(fragment4);
  1. Associate the View/Fragment and ViewPager with the corresponding Adapter adapter:
  • Pagertadapter data source: List < View >
  • FragmentPagerAdapter data source: List < fragment >
  • Fragmentstatepagertadapter data source: List < fragment > data source

Write a class that inherits the corresponding Adapter, and then rewrite the method according to the requirements. Several methods must be overridden

When the page card is View: use the viewpagertadapter:

  public class MyViewPagerAdapter extends PagerAdapter{
     private List<View> mListViews;
     public MyViewPagerAdapter(List<View> mListViews) {
        this.mListViews = mListViews;//Construction method, parameters are our page card, so it is more convenient.
     }
    //Directly inherit pagertadapter. At least the following four methods must be overridden, otherwise an error will be reported
     @Override
     public void destroyItem(ViewGroup container, int position, Object object)  {   
        container.removeView(mListViews.get(position));//Delete page card
      }

     @Override
     public Object instantiateItem(ViewGroup container, int position){
        //This method is used to instantiate the page card       
        container.addView(mListViews.get(position), 0);//Add page card
        return mListViews.get(position);
     }
     @Override
     public int getCount() {            
        return  mListViews.size();//Number of return page cards
     }
        
     @Override
     public boolean isViewFromObject(View arg0, Object arg1) {          
        return arg0==arg1;//It's official
     }
 }

When the page card is Fragment: use the FragmentAdapter:

import java.util.List;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class MyFragmentAdapter extends FragmentPagerAdapter {
    
    List<Fragment> list;

    public MyFragmentAdapter(FragmentManager fm) {
        super(fm);
    }

    public MyFragmentAdapter(FragmentManager fm,List<Fragment> list) {
        super(fm);
        this.list=list;
    }//Write the construction method to facilitate the call of assignment
    @Override
    public Fragment getItem(int arg0) {
        return list.get(arg0);
    }//Return the Fragment of corresponding position according to the position of item, bind item and Fragment

    @Override
    public int getCount() {
        return list.size();
    }//Set the number of items

}
  1. Binding Adapter in Activity

ViewPagerAdapter:

private ViewPager viewPager;

viewPager.setAdapter(new MyViewPagerAdapter(views));
viewPager.setCurrentItem(0);
viewPager.setOnPageChangeListener(new MyOnPageChangeListener());//Set the listener during page switching (optional, you need to rewrite its callback method to handle the transaction during page switching)

FragmentPagerAdapter:

vp.addOnPageChangeListener(this);//Set the listener for page switching (optional, the callback method that needs to be rewritten later to handle the transaction during page switching)
vp.setAdapter(new MyFragmentAdapter(getSupportFragmentManager(), list)
  1. Set toggle, slide animation

Use the method setPageTransformer() that comes with Viewpage to set the toggle animation

  • Step 1: define animation effect class first (the animation class provided by Google is used here)
    DepthPageTransformer.java
public class DepthPageTransformer implements ViewPager.PageTransformer {
    private static final float MIN_SCALE = 0.75f;
    public void transformPage(View view, float position) {
        int pageWidth = view.getWidth();
        if (position < -1) { // [-Infinity,-1)
            // This page is way off-screen to the left.
            view.setAlpha(0);
        } else if (position <= 0) { // [-1,0]
            // Use the default slide transition when moving to the left page
            view.setAlpha(1);
            view.setTranslationX(0);
            view.setScaleX(1);
            view.setScaleY(1);
        } else if (position <= 1) { // (0,1]
            // Fade the page out.
            view.setAlpha(1 - position);
            // Counteract the default slide transition
            view.setTranslationX(pageWidth * -position);
            // Scale the page down (between MIN_SCALE and 1)
            float scaleFactor = MIN_SCALE
                    + (1 - MIN_SCALE) * (1 - Math.abs(position));
            view.setScaleX(scaleFactor);
            view.setScaleY(scaleFactor);
        } else { // (1,+Infinity]
            // This page is way off-screen to the right.
            view.setAlpha(0);
        }
    }
}
  • Step 2: animation method call
mViewPager.setPageTransformer(true, new DepthPageTransformer());

In this way, the setup of the toggle animation is complete.

4. Similarities and differences between fragment state pager adapter and fragment pager adapter

  • with
    PageAdapter is the fragment pager adapter and
    The base class of FragmentStatePagerAdapter, which can be replaced by FragmentStatePagerAdapter

  • different
    When the fragmentpagertadapter is used, each generated Fragment will be saved in memory, while the fragmentstatepagertadapter only keeps the currently displayed Fragment, and other crossed fragments will be destroyed after leaving the line of sight. When the page needs to be displayed, it will be regenerated into a new instance.

That is, when you have a large number of pages, using the fragment state pager adapter does not need to occupy a lot of memory

Tags: Fragment Android Java xml

Posted on Mon, 29 Jun 2020 02:15:32 -0400 by zoffi