Simple use of ViewPager in Android Development

Keywords: Android Fragment

What is ViewPager?

ViewPager (android.support.v4.view.ViewPager) is a class in the Android extension package v4. This class allows users to switch the current view left and right to achieve the effect of sliding switch. Before using this class, you must understand:

  • The ViewPager class directly inherits the ViewGroup class, that is to say, it is a container like the LinearLayout we often deal with. We need to add the content we want to display in it.
  • The ViewPager class needs a PagerAdapter adapter class to provide it with data, which is similar to ListView.

Using steps

  • 1. Add in layout file
<android.support.v4.view.ViewPager 
     android:id="@+id/viewpager"     
     android:layout_width="wrap_content"    
     android:layout_height="wrap_content"   
     android:layout_gravity="center" >  
 </android.support.v4.view.ViewPager>
  • 2. Load the Views to be displayed and get Views by dynamically loading the layout
LayoutInflater lf = getLayoutInflater().from(MainActivity.this);    
View view1 = lf.inflate(R.layout.f1, null);
View view2 = lf.inflate(R.layout.f2, null);
View view3 = lf.inflate(R.layout.f3, null);
viewContainter  = new ArrayList<View>();// Load the View to be paged into the array          
viewContainter .add(view1); 
viewContainter .add(view2);
viewContainter .add(view3);
  • 3. Use PagerAdapter to associate the above View and ViewPager
//Directly inherit PagerAdapter, at least the following four methods must be overridden, otherwise an error will be reported
pager.setAdapter(new PagerAdapter()
        {

            // Total number of views to display in viewpager
            @Override
            public int getCount()
            {
                return viewContainter.size();
            }

            // Destroy the current View when sliding the switch
            @Override
            public void destroyItem(ViewGroup container, int position,
                    Object object)
            {
                container.removeView(viewContainter.get(position));
            }

            // View generated each time you slide
            @Override
            public Object instantiateItem(ViewGroup container, int position)
            {
                    container.addView(viewContainter.get(position));
                return viewContainter.get(position);
            }
           // Official advice
            @Override
            public boolean isViewFromObject(View arg0, Object arg1)
            {
                return arg0 == arg1;
            }
        });

In this way, the sliding effect can be realized

Suitable scene

  • Boot page
  • Page card slide (e.g. Netease News)

One more thing

It is officially recommended that ViewPager be used with Fragment, which will be supplemented later~~~

Posted by amir1985 on Fri, 06 Dec 2019 18:54:28 -0800