Simple use of viewpager in Android (dot at the bottom)

Source: Internet
Author: User


Bytes ~
Android. Support. v4.viewpager class in API
The 4 + support package is initially provided for us. It enables us to slide left and right to display data in the form of a 'page. We can inherit PagerAdapterTo generate a page view. Let's take a look at the effect before introducing the specific usage.

First, you must configure viewpager view in the layout file.
         <android.support.v4.view.ViewPager            android:id="@+id/pager"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginBottom="50dp" />

In fact, viewpager is essentially a view. The inheritance system is as follows. You can find that it is a viewgroup, and it has the ability to add
View

Java. Lang. Object
Bytes Android. View. View
  Bytes Android. View. viewgroup
    Bytes Android. Support. v4.view. viewpager

The above mentioned usage PagerAdapterGenerate a page view, that is, a page, PagerAdapterDetermines the total number of pages of viewpager, and is responsible for initialization and destruction of each page.
        class MyPagerAdapter extends PagerAdapter{              @Override              public int getCount() {                     return mViewList .size();             }              @Override              public Object instantiateItem(View container, int position) {                    Log. i("INFO", "instantiate item:"+position);                     ((ViewPager) container).addView( mViewList.get(position),0);                     return mViewList .get(position);             }                           @Override              public void destroyItem(View container, int position, Object object) {                    ((ViewPager) container).removeView( mViewList.get(position));              }                           @Override              public boolean isViewFromObject(View arg0, Object arg1) {                     return arg0 == arg1;             }       }


You can see that viewpager is actually a component container. You can add a view to be displayed for each page of viewpager to display data.
Mlayoutinflater = getlayoutinflater (); // You can dynamically create layout as needed. Static XML layoutmviewlist is used for the moment. add (mlayoutinflater. inflate (R. layout. per_pager1, null); mviewlist. add (mlayoutinflater. inflate (R. layout. per_pager2, null); mviewlist. add (mlayoutinflater. inflate (R. layout. per_pager3, null); viewpager = (viewpager) findviewbyid (R. id. PAGER); mpageradapter = new mypageradapter (); viewpager. setadapter (mpageradapter );

The layout of inflate above represents the layout of each page, just like the layout file we usually use... we often see that there are some dots under viewpager to indicate the page we are browsing. To achieve this effect, we need to dynamically generate the number of dots based on the number of pages, and add it to a linearlayout for ease of Management

             Bitmap bitmap = BitmapFactory. decodeResource(getResources(), R.drawable.icon_dot_normal );              for (int i = 0; i < mViewList.size(); i++) {                    Button bt = new Button(this );                    bt.setLayoutParams( new ViewGroup.LayoutParams(bitmap.getWidth(),bitmap.getHeight()));                    bt.setBackgroundResource(R.drawable. icon_dot_normal );                     mNumLayout .addView(bt);             }

How can we know the page on which the current slide is made? In fact, we can set an onpagechangelistener page change listener for viewpager to listen for page changes, so as to get the current page that slides to the page
             viewPager. setOnPageChangeListener( new OnPageChangeListener() {                                         @Override                     public void onPageSelected( int position) {                                                       if (mPreSelectedBt != null){                                   mPreSelectedBt .setBackgroundResource(R.drawable. icon_dot_normal);                           }                                                      Button currentBt = (Button)mNumLayout .getChildAt(position);                           currentBt.setBackgroundResource(R.drawable. home_page_dot_select );                            mPreSelectedBt = currentBt;                                                       //Log.i("INFO", "current item:"+position);                    }                                         @Override                     public void onPageScrolled( int arg0, float arg1, int arg2) {                            // TODO Auto-generated method stub                                               }                                         @Override                     public void onPageScrollStateChanged( int arg0) {                            // TODO Auto-generated method stub                                               }             });


Mpreselectedbt is only used to record the currently displayed dots and prepare for the next dot focus switch. The following describes a complete implementation.


Public class mainactivity extends activity {arraylist <View> mviewlist = new arraylist <View> (); layoutinflater extends; linearlayout mnumlayout; button layout; mypageradapter mpageradapter; @ bundle void oncreate (bundle release) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_main); mlayoutinflater = getlayoutinflater (); // You can dynamically create layout as needed. XML layoutmviewlist. add (mlayoutinflater. inflate (R. layout. per_pager1, null); mviewlist. add (mlayoutinflater. inflate (R. layout. per_pager2, null); mviewlist. add (mlayoutinflater. inflate (R. layout. per_pager3, null); viewpager = (viewpager) findviewbyid (R. id. PAGER); mpageradapter = new mypageradapter (); viewpager. setadapter (mpageradapter); mnumlayout = (linearlayout) findviewbyid (R. id. ll_pager_num ); Bitmap bitmap = bitmapfactory. decoderesource (getresources (), R. drawable. icon_dot_normal); For (INT I = 0; I <mviewlist. size (); I ++) {button bt = new button (this); BT. setlayoutparams (New viewgroup. layoutparams (bitmap. getwidth (), bitmap. getheight (); BT. setbackgroundresource (R. drawable. icon_dot_normal); mnumlayout. addview (BT);} viewpager. setonpagechangelistener (New onpagechangelistener () {@ overridepubli C void onpageselected (INT position) {If (mpreselectedbt! = NULL) {mpreselectedbt. setbackgroundresource (R. drawable. icon_dot_normal);} button currentbt = (button) mnumlayout. getchildat (position); currentbt. setbackgroundresource (R. drawable. home_page_dot_select); mpreselectedbt = currentbt; // log. I ("info", "current item:" + position) ;}@ overridepublic void onpagescrolled (INT arg0, float arg1, int arg2) {// todo auto-generated method stub} @ overridepublic void onpagescrollstatechanged (INT arg0) {// todo auto-generated method stub }});} class mypageradapter extends pageradapter {@ overridepublic int getcount () {return mviewlist. size () ;}@ overridepublic object instantiateitem (view container, int position) {log. I ("info", "instantiate item:" + position); (viewpager) container ). addview (mviewlist. get (position), 0); Return mviewlist. get (position) ;}@ overridepublic void destroyitem (view container, int position, object) {log. I ("info", "Destroy item:" + position); (viewpager) container ). removeview (mviewlist. get (position) ;}@ overridepublic Boolean isviewfromobject (view arg0, object arg1) {return arg0 = arg1 ;}}}

If you carefully observe and print the log, you will find that the implementation of pageradapter is somewhat special and there will always be two initialized 'page' (page> 2 ), the next page is initialized when the current page is displayed, and the previous page is destroy. The following figure shows the printed information after one slide.

04-02 22:39:59.880: I/INFO(27187): instantiate item:004-02 22:39:59.880: I/INFO(27187): instantiate item:104-02 22:40:03.890: I/INFO(27187): instantiate item:204-02 22:40:39.020: I/INFO(27187): destroy item:0

When the page number to be displayed changes, we can call the notifydatasetchanged () of pageradapter to notify the Data Change (update must be notified in the UI main thread), and the dot must also be updated.

mViewList.add(mLayoutInflater.inflate(R.layout.per_pager1, null));Button bt = new Button(this);bt.setLayoutParams(new ViewGroup.LayoutParams(bitmap.getWidth(),bitmap.getHeight()));bt.setBackgroundResource(R.drawable.icon_dot_normal);mNumLayout.addView(bt);mPagerAdapter.notifyDataSetChanged();

The above is basically the basic usage of viewpager, which is relatively simple, but the most common use of viewpager is the combinationFragmentIn this way, you can easily manage the lifecycle of each page. Android also provides us with some fixed implementations of adapters for viewpager. They includeFragmentPagerAdapter,FragmentStatePagerAdapter,FragmentPagerAdapter,
AndFragmentStatePagerAdapterEach of them can write a small amount of simple code to create a complete user interface for us. The next section will introduce






Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.