In the first launch of many apps will appear the boot page, in some apps will also include some left and right sliding pages and page carousel switch situation. have also learned Adapterviewflipper and Viewflipper before, can be very good implementation, today continue to learn a more powerful Viewpager components.
I. Introduction of Viewpager
Viewpager is the class in the Android Expansion Pack V4 package that allows users to swipe left and right to toggle the current view. Viewpager inherits from ViewGroup, that is, Viewpager is a container class that can contain other view classes.
The main methods of Viewpager are as follows:
Setadapter (Pageradapter adapter): Set the adapter for Viewpager, Viewpager has three adapters, including Pageradapter, Fragmentpageradapter, Fragmentstatepageradapter, they each have different characteristics, this period will first come to learn pageradapter.
Setcurrentitem (int Item): Sets the interface that displays the item location.
Setoffscreenpagelimit (int limit): Used to set the number of pages that are cached on the left and right sides of the currently displayed page.
Addonpagechangelistener (Onpagechangelistener Listener): Listens for Viewpager when a page switch is added.
For the content of the interface listening, then the method in Onpagechangelistener is explained:
onpagescrollstatechanged (int state): This method changes when the finger is manipulating the screen. There are three values: 0 (END), 1 (Press), 2 (UP). When you swipe the page with your finger, the method triggers when the finger is pressed, the state value is 1, and when the finger is lifted, if a slide (even if it's small) occurs, the value changes to 2 and then finally to 0. This method is performed three times in total. A special case is that the finger is pressed down a little bit after the slide did not happen, this time only call this method two times, the state value is 1, 0. When Setcurrentitem turns the page, this method is executed two times, with state values of 2 and 0, respectively.
onpagescrolled (int position, float positionoffset, int positionoffsetpixels): This method is always called during the sliding process, and the parameters of the method are described as follows:
Position: When you swipe with your finger, if your finger presses on the page, the position is consistent with the current page index, and if you drag the finger to the left (the corresponding page flips to the right), position most of the time is consistent with the current page, Only the last call will be made to the target page if the paging is successful, and if the finger is dragged to the right (the corresponding page is flipped to the left), the position most of the time is consistent with the target page, and the last call will change to the original page only if the paging is unsuccessful. When the direct set Setcurrentitem page, if it is adjacent to the situation (such as now the second page, jump to the first or third page), if the page to the right, most of the time is the same as the current page, only the last to become the target page; The position and target pages are consistent. This is basically the same as dragging the page with your finger. If it is not adjacent, such as I jump from the first page to the third page, position first 0, then gradually become 1, and then gradually become 2; I jump from the third page to the first page, position 1, and then gradually become 0, and there is no case of 2.
Positionoffset: The current page sliding scale, if the page is flipped to the right, this value continues to grow, and finally in the case of approaching 1, the mutation is 0. If the page is flipped to the left, the value continues to become smaller and then 0.
Positionoffsetpixels: The current page slides pixels, and the change is consistent with Positionoffset.
onpageselected (int position): position is the index of the selected page, which is called when the page is selected or the page slides enough distance to switch to the page's finger lift.
The order of execution of the above three methods: When you drag the page with your finger, first execute the onpagescrollstatechanged (1), and then continue to execute onpagescrolled, when you let go, Executes the onpagescrollstatechanged (2) immediately, then executes the onpageselected immediately, then executes the onpagescrollstatechanged again, The last time onpagescrollstatechanged (0) is executed.
In most controls that use adapters, the adapter is more complex than the data source and view, and it also determines the main functionality of the control, and Viewpager is no exception. When implementing a pageradapter, you need to rewrite at least the following 4 methods:
GetCount (): Returns the number of valid views.
Isviewfromobject (View, Object): Determines whether a page View is associated with the specific key object returned by the Instantiateitem (viewgroup, int) method.
Instantiateitem (viewgroup, int): Creates a page view at the specified location. It is the responsibility of the adapter to add the view view that is about to be created to the given container, making sure that when Finishupdate (ViewGroup) is returned, the addition of the views is complete.
Destroyitem (viewgroup, int, Object): Removes the view at the given position, the adapter is responsible for removing the view from the container, ensuring that when finishupdate (ViewGroup) returns, The thing to remove the view is complete.
In addition to the above 4 methods, there are several methods that can be rewritten according to actual needs.
GetItemPosition (Object object): Called when the host view tries to determine whether the position of an item has changed. Returns position_unchanged if the position of the given item does not change, or Position_none if the item no longer exists in the adapter specific adapter.
Startupdate (ViewGroup container): Called when a change in the displayed interface is about to occur.
Finishupdate (ViewGroup container): Called when the changes in the display interface are complete. At this point in time, you must make sure that all pages have been properly added or removed from the container.
Notifydatasetchanged (): This method is actively invoked by the application when the adapter data changes.
Registerdatasetobserver (Datasetobserver observer): Registers an observer to receive callbacks associated with changes to the adapter data.
Unregisterdatasetobserver (Datasetobserver observer): Anti-registration to receive observers associated with the callback for data changes in the adapter.
Setprimaryitem (ViewGroup container, int position, Object object): Call this method to notify the current adapter which item is considered "primary", which is the page currently displayed to the user.
Getpagetitle (int position): This method is called by Viewpager when it gets the caption of the page described, and null is returned by default.
Getpagewidth (int position): This method returns the scale width, range (0.f-1.f] of a given page.
SaveState (): Saves the instance state associated with the adapter and resumes when the current UI state needs to be rebuilt.
Restorestate (parcelable State, ClassLoader loader): Restores the instance status associated with the adapter previously saved by SaveState ().
The specific use of Viewpager is similar to the list class component that was previously learned, first constructing the adapter, then providing the data source, and finally loading the adapter.
Ii. Examples of Viewpager
Next, a simple example program is used to learn the use of Viewpager.
Continue to use the Advancedviewsample module of the Widgetsample project to create a viewpager_layout.xml file in the app/main/res/layout/directory populated with the following code snippet:
<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"android:orientation= "vertical"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"> <Android.support.v4.view.ViewPagerAndroid:id= "@+id/view_pager"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"> </Android.support.v4.view.ViewPager></LinearLayout>
Then create a few page files, the first page named Viewpager_pager1.xml, the code is as follows:
<?XML version= "1.0" encoding= "Utf-8"?><Relativelayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"> <ImageViewAndroid:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"android:layout_centerinparent= "true"android:src= "@drawable/image_01"/></Relativelayout>
Another 3 new, for a simple layout and the same as above, the code loaded in the picture can be changed.
Create a new Viewpageradapter class, inherit the Pageradapter, and override its method with the following code:
PackageCom.jinyu.cqkxzsxy.android.advancedviewsample.adapter;ImportAndroid.support.v4.view.PagerAdapter;ImportAndroid.view.View;ImportAndroid.view.ViewGroup;Importjava.util.ArrayList;/*** @ Creator Xin 鱻 * @ description Android 0 Basic primer to Master Series Tutorial * Starting public number sharing talent Show (Shareexpert)*/ Public classViewpageradapterextendsPageradapter {PrivateArraylist<view> mpagelist =NULL; PublicViewpageradapter (arraylist<view>pagelist) { This. mpagelist =pagelist; } @Override Public intGetCount () {returnmpagelist.size (); } @Override Public Booleanisviewfromobject (View view, Object object) {returnView = =object; } @Override PublicObject Instantiateitem (ViewGroup container,intposition) {View PageView=Mpagelist.get (position); Container.addview (PageView); returnPageView; } @Override Public voidDestroyitem (ViewGroup container,intposition, Object object) { //Remove the view from the current locationContainer.removeview (mpagelist.get (position)); }}
Create a new Viewpageractivity.java file and load the new layout file above, with the following code:
Package Com.jinyu.cqkxzsxy.android.advancedviewsample;import Android.os.bundle;import Android.support.v4.view.viewpager;import Android.support.v7.app.appcompatactivity;import Android.view.layoutinflater;import Android.view.view;import Android.widget.toast;import Com.jinyu.cqkxzsxy.android.advancedviewsample.adapter.viewpageradapter;import java.util.ArrayList;/** * @ Creator Xin 鱻 * @ Description Android 0 Basics to Master Series tutorials, welcome to public number Shareexpert */public class Viewpageractivity extends Appcompatactivity implements Viewpager.onpagechangelistener {private Viewpager mviewpager = null; Private Viewpageradapter madapter = null; Private arraylist<view> mpagelist = null; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.viewpager_layout); Mviewpager = (Viewpager) Findviewbyid (R.id.view_pager); Mpagelist = new arraylist<> (); Layoutinflater inflater = Getlayoutinflater (); Mpagelist.aDD (inflater.inflate (R.layout.viewpager_page1, NULL, false)); Mpagelist.add (inflater.inflate (R.layout.viewpager_page2, NULL, false)); Mpagelist.add (inflater.inflate (R.layout.viewpager_page3, NULL, false)); Mpagelist.add (inflater.inflate (R.layout.viewpager_page4, NULL, false)); Madapter = new Viewpageradapter (mpagelist); Mviewpager.setadapter (Madapter); Mviewpager.addonpagechangelistener (this); } @Override public void onpagescrolled (int position, float positionoffset, int positionoffsetpixels) {} @Over Ride public void onpageselected (int. position) {Toast.maketext (this, "No." + (position + 1) + "page", Toast.length_sh ORT). Show (); } @Override public void onpagescrollstatechanged (int state) {}}
Modify the program start activity, run the program, and then swipe left and right to see the interface effect shown.
Do not know if you find out, this is not our common application launch when the boot page, but the example is relatively simple, there is no page instruction guide, this piece of follow-up learning and then gradually to optimize the completion.
Come here today, if you have any questions welcome message to discuss together, also welcome to join the Android 0 Basic introductory Technical discussion group, grow together!
This article copyright for the public Share talent show (Shareexpert)--Xin 鱻 all, if necessary reprint please contact the author authorized, hereby declare!
Past period Summary share:
Android 0 Basics Introduction 1th: Android's past life
Android 0 Basics Section 2nd: Android system Architecture and application components those things
Android 0 Basics Section 3rd: Bring you up to talk about Android development environment
Android 0 Basics 4th: Installing and configuring the JDK correctly Ko fu the first trick
Android 0 Basics 5th: Use ADT bundles to easily meet the goddess
Android 0 Basics 6th: Configuration Optimization SDK Manager, official dating goddess
Android 0 Basics 7th: Take care of Android simulator and start the Sweet journey
Android 0 Basics 8th: HelloWorld, the starting point for my first trip
Android 0 Basics 9th: Android app, no code can be developed
Android 0 Basics Section 10th: Development IDE Big upgrade, finally ushered in Android Studio
Android 0 Basics Introductory Section 11th: Simple steps to take you to fly, run Android Studio project
Android 0 Basics 12th: Get familiar with the Android studio interface and start selling
Android 0 Basics 13th: Android Studio Personalized configuration to create a tool for development
Android 0 Basics 14th: Using high-speed genymotion, stepping into the rocket era
Android 0 Basics Section 15th: Mastering the Android Studio project structure, sailing
Android 0 Basics Section 16th: Android User Interface Development overview
Android 0 Basics Section 17th: text box TextView
Android 0 Basics Section 18th: Input box EditText
Android 0 Basics Get started section 19th: Buttons button
Android 0 Basics 20th: check box checkbox and radio button radiobutton
Android 0 Basics Section 21st: Switch Components ToggleButton and switch
Android 0 Basics Section 22nd: Image View ImageView
Android 0 Basics Section 23rd: Image button ImageButton and zoom button Zoombutton
Android 0 Basics Section 24th: Customize view simple to use to create your own controls
Android 0 Basics Section 25th: Simple and most commonly used linearlayout linear layouts
Android 0 Basics Section 26th: Two alignments, layout_gravity and gravity differ greatly
Android 0 Basics section 27th: Using padding and margin correctly
Android 0 Basics Section 28th: Easy to master relativelayout relative layout
Android 0 Basics 29th: Use tablelayout table layouts
Android 0 Basics 30th: Two minutes master Framelayout frame layout
Android 0 Basics Section 31st: absolutelayout absolute Layout with less
Android 0 Basics Section 32nd: New GridLayout Grid layout
Android 0 Basics section 33rd: Android Event Handling overview
Android 0 Basics Section 34th: Listening-based event handling in Android
Android 0 Basics Section 35th: Callback-based event handling in Android
Android 0 Basics Section 36th: Handling of Android system events
Android 0 Basics 37th: First Knowledge ListView
Android 0 Basics 38th: First Knowledge Adapter
Android 0 Basics section 39th: listactivity and custom list items
Android 0 Basics Section 40th: Customizing Arrayadapter
Android 0 Basics Section 41st: Using Simpleadapter
Android 0 Basics Section 42nd: Customizing Baseadapter
Android 0 Basics section 43rd: ListView Optimization and List End-to-end use
Android 0 Basics Section 44th: ListView Data Dynamic Update
Android 0 Basic Getting Started section 45th: Grid view GridView
Android 0 Basics section 46th: List Options Box spinner
Android 0 Basic Getting Started section 47th: AutoComplete text Box Autocompletetextview
Android 0 Basics Section 48th: Collapsible list Expandablelistview
Android 0 Basics section 49th: Adapterviewflipper picture Carousel
Android 0 Basics Section 50th: StackView card Stacking
Android 0 Basics Section 51st: progress bar ProgressBar
Android 0 Basics section 52nd: Customizing ProgressBar Cool progress bar
Android 0 Basics 53rd: Drag bar Seekbar and star rating bar Ratingbar
Android 0 Basics section 54th: View switch Components Viewswitcher
Android 0 Basics Section 55th: Imageswitcher and Textswitcher
Android 0 Basics Section 56th: Flip View Viewflipper
Android 0 Basics Section 57th: DatePicker and Timepicker selectors
Android 0 Basics Section 58th: Value selector numberpicker
Android 0 Basics Section 59th: Common Three clock clocks components
Android 0 Basics Section 60th: Calendar view CalendarView and timer chronometer
Android 0 Basics Section 61st: Scrolling view ScrollView
Android 0 Basics section 62nd: Search box Component Searchview
Android 0 Basics Introductory Section 63rd: Learn from the tab tabhost
Android 0 Basics 64th: Uncover Recyclerview
Android 0 Basics Section 65th: Recyclerview Split Line Development tips
Android 0 Basics Section 66th: Recyclerview Click event Handling
Android 0 Basics Section 67th: Recyclerview Data Dynamic Update
Android 0 Basics 68th: Recyclerview adding end-to-end views
Android 0 Basics Section 69th: Viewpager Quick Implementation Guide page