Use ViewPager in Android to create an advertisement bar effect-Solve the Problem of ViewPager full screen page adaptation

Source: Internet
Author: User

.

Reference page: advertisement bar on the Ctrip app homepage, which is implemented using ViewPager

 

Homemade page:

 

 

.

 

I. ViewPager page adaptation problems

 

1. Problems with ViewPager

 

Full Screen ViewPager: ViewPager defines android: layout_height and android: layout_width in XML. no matter whether the values of these two attributes are fill_parent or wrap_content, ViewPager occupies full screen;

 

Do not use a fixed value to define the width and height: To enable ViewPager to adapt to various types of mobile phones, ifDefines the height and width for ViewPager., And various mobile phone InterfacesCompatibility must be greatly reducedAs a result, the following solution emerged;

 

2. Solution

 

Add components to the code: This component is not defined on the XML interface. It can be found in the layout file,Define a LinearLayout container and dynamically add ViewPager to the code;

Benefits: The advantage is that the screen width and height can be obtained in the code. We can set the ViewPager size according to the ratio, which solves the problem of screen adaptation;

 

3. Code Implementation

 

 

// Obtain the ViewPager parent container pagerLayout = (LinearLayout) findViewById (R. id. view_pager_content); // create ViewPager adViewPager = new ViewPager (this); // obtain the display pixel information DisplayMetrics dm = new DisplayMetrics (); getWindowManager (). getdefadisplay display (). getMetrics (dm); // set the width and height of the ViewPager ad container Based on the screen information. setLayoutParams (new LayoutParams (dm. widthPixels, dm. heightPixels * 2/5); // set the ViewPager container to pagerLayout in the parent container of the layout file. addView (adViewPager );


 

 

Ii. Basic solutions for ViewPager advertising bar

 

1. ViewPager adapter PagerAdapter

 

Custom PagerAdapter class: We need to customize a class to inherit the PageAdapter, at least implement the following four methods:

 

DestroyItem (View container, int position, Object object):

Function:Delete the page at the specified position in the container;

Parameters: Container is the container. Here it refers to the ViewPager object, and position is the deleted page index;

 

Int getCount ():

Function:Obtain the number of ViewPager pages;

Return Value: Number of ViewPager pages;

 

Object instantiateItem (View container, int position):

Function:PageAdapter is responsible for adding a View page to a specified position when creating a page at a given position.;

Parameters: The container is ViewPager, and position indicates the index of ViewPager;

Return Value: Returns an object representing a new page;

 

Boolean isViewFromObject (View view, Object object):

Function:DecisionWhether the Object returned by the instantiateItem () method is a page association that needs to be displayed. This method must have;

Parameters: View the page to be associated, the object returned by the object instantiateItem () method;

Return Value: Whether to associate display page with instantiateItem () return value;

 

Associate a data source with PageAdapter: You can associate an array or set with PageAdapter,The index of the set corresponds to the index of ViewPager., The destroyItem () method deletes the Element Object of the corresponding index in the set, and the instantiateItem adds the Element Object of the corresponding index;

 

PageAdapter code example:

 

Private final class AdvAdapter extends PagerAdapter {private List
 
  
Views = null;/*** initialize the data source, that is, the View array */public AdvAdapter (List
  
   
Views) {this. views = views;}/*** Delete the View Object corresponding to the index from the ViewPager Set */@ Override public void destroyItem (View container, int position, object Object object) {(ViewPager) container ). removeView (views. get (position);}/*** get the number of ViewPager */@ Override public int getCount () {return views. size ();}/*** get the corresponding index element from the View set and add it to ViewPager */@ Override public Object instantiateItem (View container, int position) {(ViewPager) container ). addView (views. get (position), 0); return views. get (position);}/*** whether to associate the displayed ViewPager page with the object returned by instantiateItem * This method is required */@ Override public boolean isViewFromObject (View view View, object object) {return view = object ;}}
  
 

Create PageAdapter code:

 

 

 

private void initPageAdapter() {pageViews = new ArrayList
 
  ();ImageView img1 = new ImageView(this);          img1.setBackgroundResource(R.drawable.view_add_1);          pageViews.add(img1);                  ImageView img2 = new ImageView(this);          img2.setBackgroundResource(R.drawable.view_add_2);          pageViews.add(img2);                 ImageView img3 = new ImageView(this);          img3.setBackgroundResource(R.drawable.view_add_3);          pageViews.add(img3);                 ImageView img4 = new ImageView(this);          img4.setBackgroundResource(R.drawable.view_add_4);          pageViews.add(img4);                 ImageView img5 = new ImageView(this);          img5.setBackgroundResource(R.drawable.view_add_5);          pageViews.add(img5);                 ImageView img6 = new ImageView(this);          img6.setBackgroundResource(R.drawable.view_add_6);          pageViews.add(img6);                  adapter = new AdPageAdapter(pageViews);}
 

 

2. Small dot navigation policy

 

Dot Storage Policy: All the small dots are placed in a ViewGroup. There are two kinds of dots, one is currently displayed, the other is not activated. Here we will put a group of dotsPut them in ImageViewAnd set these imageviewsAssemble and put it in ViewGroupYou can;

 

Dot navigation Initialization: The first page is displayed by default. The first dot is activated. The number of dots is initialized based on the number of ViewPager. When the dot is assembled, the first dot is activated;

The Code is as follows::

 

Private void initCirclePoint () {ViewGroup group = (ViewGroup) findViewById (R. id. viewGroup); imageViews = new ImageView [pageViews. size ()]; // The dot icon in the ad bar for (int I = 0; I <pageViews. size (); I ++) {// create an ImageView and set the width and height. put this object into the array imageView = new ImageView (this); imageView. setLayoutParams (new LayoutParams (20, 20); imageViews [I] = imageView; // initial value. The default value is 0th if (I = 0) {imageViews [I]. setBackgroundResource (R. drawable. point_focused);} else {imageViews [I]. setBackgroundResource (R. drawable. point_unfocused);} // place the dot in the layout group. addView (imageViews [I]);}


 

When the ViewPager page changes, the dot navigation changes accordingly.: Retrieve the index of the current display page of ViewPager,Reassemble the dot arrangement order in the ViewGroupIn ViewPagerPage change listener;

The Code is as follows::

 

/*** ViewPager page change listener */private final class AdPageChangeListener implements OnPageChangeListener {/*** trigger when the page rolling status changes */@ Override public void onPageScrollStateChanged (int arg0) {}/*** trigger when page rolling */@ Override public void onPageScrolled (int arg0, float arg1, int arg2) {}/*** trigger when the page is selected */@ Override public void onPageSelected (int arg0) {// obtain the atomicInteger of the currently displayed page. getAndSet (arg0); // Reset Origin layout set for (int I = 0; I <imageViews. length; I ++) {imageViews [arg0]. setBackgroundResource (R. drawable. point_focused); if (arg0! = I) {imageViews [I]. setBackgroundResource (R. drawable. point_unfocused );}}}}


 

3. Automatic paging navigation policy

 

Automatic page turning in thread processing: Start a thread, obtain the index displayed on the current page, calculate the next display location, and display the next page;

.

Related code:

Thread code:

 

    new Thread(new Runnable() {              @Override              public void run() {                  while (true) {                      if (isContinue) {                          viewHandler.sendEmptyMessage(atomicInteger.get());                          atomicOption();                      }                  }              }          }).start();  

Handler code:

 

 

Private void atomicOption () {atomicInteger. incrementAndGet (); if (atomicInteger. get ()> imageViews. length-1) {atomicInteger. getAndAdd (-5);} try {Thread. sleep (3000);} catch (InterruptedException e) {}}/** switch the advertisement bar image at regular intervals */private final Handler viewHandler = new Handler () {@ Override public void handleMessage (Message msg) {adViewPager. setCurrentItem (msg. what); super. handleMessage (msg );}};


 

3. All code and resource files of the program

 

XML layout File:

 

 
         
                    
                    
              
          
   
           
      
      
 


 

Main Activity source code:

 

Package shuliang. han. myviewpager; import java. util. arrayList; import java. util. list; import java. util. concurrent. atomic. atomicInteger; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. support. v4.view. pagerAdapter; import android. support. v4.view. viewPager; import android. support. v4.view. viewPager. onPageChangeListener; import android. util. displayMetrics; import android. view. view; import android. view. viewGroup; import android. view. viewGroup. layoutParams; import android. widget. imageView; import android. widget. linearLayout; public class MainActivity extends Activity {private ViewPager adViewPager; private LinearLayout pagerLayout; private List
 
  
PageViews; private ImageView [] imageViews; private ImageView imageView; private AdPageAdapter adapter; private AtomicInteger atomicInteger = new AtomicInteger (0); private boolean isContinue = true; @ override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); initViewPager ();} private void initViewPager () {// obtain the ViewPager parent container pagerLayout = (LinearLayout) findViewById (R. id. view_pager_content); // create ViewPager adViewPager = new ViewPager (this); // obtain the display pixel information DisplayMetrics dm = new DisplayMetrics (); getWindowManager (). getdefadisplay display (). getMetrics (dm); // set the width and height of the ViewPager ad container Based on the screen information. setLayoutParams (new LayoutParams (dm. widthPixels, dm. heightPixels * 2/5); // set the ViewPager container to pagerLayout in the parent container of the layout file. addView (adViewPager); initPageAdapter (); initCirclePoint (); adViewPager. setAdapter (adapter); adViewPager. setOnPageChangeListener (new AdPageChangeListener (); new Thread (new Runnable () {@ Override public void run () {while (true) {if (isContinue) {viewHandler. sendEmptyMessage (atomicInteger. get (); atomicOption ();}}}}). start ();} private void atomicOption () {atomicInteger. incrementAndGet (); if (atomicInteger. get ()> imageViews. length-1) {atomicInteger. getAndAdd (-5);} try {Thread. sleep (3000);} catch (InterruptedException e) {}}/** switch the advertisement bar image at regular intervals */private final Handler viewHandler = new Handler () {@ Override public void handleMessage (Message msg) {adViewPager. setCurrentItem (msg. what); super. handleMessage (msg) ;}}; private void initPageAdapter () {pageViews = new ArrayList
  
   
(); ImageView img1 = new ImageView (this); img1.setBackgroundResource (R. drawable. view_add_1); pageViews. add (img1); ImageView img2 = new ImageView (this); img2.setBackgroundResource (R. drawable. view_add_2); pageViews. add (img2); ImageView img3 = new ImageView (this); img3.setBackgroundResource (R. drawable. view_add_3); pageViews. add (img3); ImageView img4 = new ImageView (this); img4.setBackgroundResource (R. d Rawable. view_add_4); pageViews. add (img4); ImageView img5 = new ImageView (this); img5.setBackgroundResource (R. drawable. view_add_5); pageViews. add (img5); ImageView img6 = new ImageView (this); img6.setBackgroundResource (R. drawable. view_add_6); pageViews. add (img6); adapter = new AdPageAdapter (pageViews);} private void initCirclePoint () {ViewGroup group = (ViewGroup) findViewById (R. id. viewGroup); imageVi Ews = new ImageView [pageViews. size ()]; // The dot icon in the ad bar for (int I = 0; I <pageViews. size (); I ++) {// create an ImageView and set the width and height. put this object into the array imageView = new ImageView (this); imageView. setLayoutParams (new LayoutParams (0th); imageViews [I] = imageView; // initial value. The default value is if (I = 0) {imageViews [I]. setBackgroundResource (R. drawable. point_focused);} else {imageViews [I]. setBackgroundResource (R. drawable. point_u Nfocused);} // place the dot into the layout group. addView (imageViews [I]);} /*** ViewPager page change listener */private final class AdPageChangeListener implements OnPageChangeListener {/*** trigger when the page rolling status changes */@ Override public void onPageScrollStateChanged (int arg0) {}/*** trigger when page rolling */@ Override public void onPageScrolled (int arg0, float arg1, int arg2) {}/*** trigger when the page is selected */@ Override public void onPageSelected (int ar G0) {// obtain the page atomicInteger that is currently displayed. getAndSet (arg0); // reset the origin layout set for (int I = 0; I <imageViews. length; I ++) {imageViews [arg0]. setBackgroundResource (R. drawable. point_focused); if (arg0! = I) {imageViews [I]. setBackgroundResource (R. drawable. point_unfocused) ;}}} private final class AdPageAdapter extends PagerAdapter {private List
   
    
Views = null;/*** initialize the data source, that is, the View array */public AdPageAdapter (List
    
     
Views) {this. views = views;}/*** Delete the View Object corresponding to the index from the ViewPager Set */@ Override public void destroyItem (View container, int position, object Object object) {(ViewPager) container ). removeView (views. get (position);}/*** get the number of ViewPager */@ Override public int getCount () {return views. size ();}/*** get the corresponding index element from the View set and add it to ViewPager */@ Override public Object instantiateItem (View container, int position) {(ViewPager) container ). addView (views. get (position), 0); return views. get (position);}/*** whether to associate the displayed ViewPager page with the object returned by instantiateItem * This method is required */@ Override public boolean isViewFromObject (View view View, object object) {return view = object ;}}}
    
   
  
 


 

:

 

Source code: Http://download.csdn.net/detail/han1202012/6835401

.

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.