Android uses Viewpager to achieve screen page switching and page carousel effects _android

Source: Internet
Author: User
Tags object object

Earlier on how to implement screen page switching, wrote a blog post "Android using Viewflipper to achieve screen switching," compared to viewflipper,viewpager more complex view switching, and Viewpager have their own adapter, This also lets it adapt to the complex object, realizes the data dynamic loading.

Viewpager is a software package that Google has provided us with a compatible version of a low-level Android device that contains only the APIs that are available in Android more than 3.0. And Viewpager is one of them, using it, we can do a lot of things, from the simplest navigation, to the page menu and so on.

Below we show two simple effects that viewpager can achieve:

The first: The screen of the page to switch (similar to the Viewflipper implementation effect)

The implementation effect is as follows (4 views (layout)):

Step One: Add the main layout file to the layout layout file Viewpager_layout.xml

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns: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.viewpager
android:layout_width=" Match_parent "
android:layout_height= "Match_parent"
android:layout_gravity= "center"
android:gravity= "center
" Android:id= "@+id/vp" >
<android.support.v4.view.pagertabstrip
android:layout_width= "Match_ Parent "
android:layout_height=" wrap_content "
android:id=" @+id/tap ">
</ android.support.v4.view.pagertabstrip>
</android.support.v4.view.ViewPager>
</ Linearlayout>

Precautions:

<1, here Viewpager and Pagertabstrip all have to write the bag name, otherwise will ClassNotFound

<2, API said: In the layout of XML Pagertabstrip as a viewpager of a child tag to use, can not take out, or it will be an error

<3, you can use attributes in Pagertabstrip tags android:layout_gravity=top| Bottom to specify the title position

<4, if you want to display the title of a Pagertabstrip page, you need to implement Getpagetitle (int) in the adapter of Viewpager

Step Two: Create a view file to show the switch in Layout (sample four Layout1/2/3/4.xml, write a typical here):

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
"http://schemas.android.com/apk/" Res/android "
xmlns:app=" Http://schemas.android.com/apk/res-auto "
android:orientation=" vertical "Android : layout_width= "match_parent"
android:layout_height= "match_parent" >
<imageview
android:layout _width= "Match_parent"
android:layout_height= "match_parent"
android:src= "@mipmap/a1"
android: Scaletype= "Centercrop"
android:id= "@+id/iv1"/>
</LinearLayout>

Step Three: The implementation code for the activity in Java Viewpagerdemo.java (no Pagertabstrip properties are set here):

Instantiate the Viewpager component in the activity and set its adapter (that is Pageradapter, method is the same as ListView)

Implement a pageradapter that overrides the following methods:

Instantiateitem (viewgroup, int)//To instantiate the page card

Destroyitem (viewgroup, int, Object)//delete page card

GetCount ()///Return number of page cards

Isviewfromobject (View, object)//Judge whether two objects are equal

Getpagetitle (int position)//Set label display caption

Set a property that indicates a label

Color of the Pagertabstrip.settabindicatorcolor ()//indicator

Pagertabstrip.setbackgroundcolor ()//Background color

Pagertabstrip.settextcolor (Color.White);//Font Color

Import Android.os.Bundle;
Import android.support.annotation.Nullable;
Import Android.support.v4.view.PagerAdapter;
Import Android.support.v4.view.ViewPager;
Import android.support.v7.app.AppCompatActivity;
Import Android.view.View;
Import Android.view.ViewGroup;
Import java.util.ArrayList;
/** * Created by Panchengjia on 2016/12/1. * * public class Viewpagerdemo extends Appcompatactivity {private Viewpager VP;//Declare a collection of stored Viewpager views arraylist<view& Gt
views = new arraylist<> ();
Display the title of each view in the effect string[] titles={"A beauty", "Number second beauty", "Third Beauty", "Fourth Beauty"};
@Override protected void OnCreate (@Nullable Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Setcontentview (r.layout.viewpager_layout);
vp= (Viewpager) Findviewbyid (R.ID.VP); Initview ()//Call the initialization view method Vp.setadapter (New Myadapter ());//Set the method of the adapter}//Initialize view (get the view used for sliding by the layout shim and deposit the corresponding collection) private void
Initview () {View v1 = Getlayoutinflater (). Inflate (R.layout.layout1,null);
View v2 = Getlayoutinflater (). Inflate (R.layout.layout2,null); ViEW v3 = Getlayoutinflater (). Inflate (R.layout.layout3,null);
View v4 = Getlayoutinflater (). Inflate (R.layout.layout4,null);
Views.add (v1);
Views.add (v2);
Views.add (v3);
Views.add (v4); Class Myadapter extends pageradapter{@Override public int GetCount () {return views.size ();} @Override public Boolean
Isviewfromobject (view, object) {return View==object}//override Destroy Slide view layout (Move child view out of view storage collection (ViewGroup)) @Override
public void Destroyitem (ViewGroup container, int position, object object) {Container.removeview (views.get));
Overrides initialize the slide view layout (remove the corresponding view from the View collection, add to ViewGroup) @Override public Object instantiateitem (viewgroup container, int position) {
View v =views.get (position);
Container.addview (v);
return v;
@Override public charsequence getpagetitle (int position) {return titles[position];} }

Second: page Carousel effect View (the first boot page implementation of the program)

The implementation effect is as follows (3 views slide boot):

Before starting code comment:

1, this time does not realize the circular carousel effect; 2, navigation origin resource picture annotation: Default_holo is unchecked, Touched_holo is a solid state when selected. (can also be drawn by shape)

Step One: Add the main layout file to the layout layout file Viewpager_layout.xml

The main layout is framelayout, where the LinearLayout layout with 3 navigation origin (determined by the number of sliding views) is nested on Viewpager (where the navigation origin is present and not set Pagertabstrip) (This is the bottom of the layout):

<?xml version= "1.0" encoding= "Utf-8"?> <framelayout xmlns:android= "http://schemas.android.com/apk/res/" Android "xmlns:tools=" Http://schemas.android.com/tools "android:id=" @+id/activity_main "android:layout_width=" Match_parent "android:layout_height=" Match_parent "tools:context=" Com.example.administrator.myapplication11.MainActivity "> <android.support.v4.view.viewpager android:layout _width= "Match_parent" android:layout_height= "match_parent" android:id= "@+id/vp" > </ android.support.v4.view.viewpager> <linearlayout android:id= "@+id/point_layout android:layout_width=" match _parent "android:layout_height=" wrap_content "android:layout_gravity=" bottom "android:orientation=" horizontal "
> <imageview android:layout_width= "0dp" android:layout_height= "Wrap_content" android:layout_weight= "1" android:src= "@mipmap/default_holo"/> <imageview android:layout_width= "0DP" android:layout_height= "WRAP_" Content "android:layout_weight=" 1 "android:src=" "@mipmap/default_holo"/> <imageview android:layout_width= "0DP" android:layout_height= "Wrap_content" android:layout_weight= "1" android:src= "@mipmap/default_holo" android:id= "@+id/imageview"/> </LinearLayout> </FrameLayout>

Step two: The view in the layout for sliding transitions (examples of the three layout1/2/3.xml, which write a typical here) are the same as the first

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
"http://schemas.android.com/apk/" Res/android "
android:orientation=" vertical "android:layout_width=" match_parent "
android:layout_height=" Match_parent ">
<imageview
android:layout_width=" match_parent "
android:layout_height=" Match_ Parent "
android:scaletype=" Centercrop "
android:src=" @mipmap/genie "/>
</LinearLayout>

Step Three: The implementation code of the activity in Java Mainactivity.java

Through the implementation of the Onpagechangelistener interface in the view of the switch to navigate the origin of the change in the state of the original point, the Onpagechangelistener in the detailed explanation of the method, please refer to the blog

"Viewpager's Setonpagechangelistener method detailed" Here do not repeat:

Import Android.support.v4.view.PagerAdapter;
Import Android.support.v4.view.ViewPager;
Import android.support.v7.app.AppCompatActivity;
Import Android.os.Bundle;
Import Android.view.View;
Import Android.view.ViewGroup;
Import Android.widget.ImageView;
Import Android.widget.LinearLayout;
Import java.util.ArrayList;
/** * Created by Panchengjia on 2016/11/30. * * public class Mainactivity extends appcompatactivity implements viewpager.onpagechangelistener{private Viewpager VP; p
Rivate LinearLayout point_layout;
arraylist<view> views =new arraylist<> ();
The set of materialized storage ImageView (navigation origin) arraylist<imageview> imageviews = new arraylist<> (); int currimage;//records the current page (navigation origin) @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (
Savedinstancestate);
Setcontentview (R.layout.activity_main);
vp= (Viewpager) Findviewbyid (R.ID.VP);
Initview ()//calls the initialization view method Initpoint ();//calls the method that initializes the navigation Origin Vp.addonpagechangelistener (this);
Vp.setadapter (New Myadapter ()); }/* Will Point_layoutImageView (navigation origin) included in the Imageviews collection * and set LAYOUT1 (first view) navigation origin (corresponding to set 0 subscript) picture * for Touched_holo (touch State of the picture) * * * private void Initpoint () {point_layout= (linearlayout) Findviewbyid (r.id.point_layout); int counnt = Point_layout.getchildcount () ;//Get point quantity for (int i=0;i<counnt;i++) {imageviews.add (ImageView) Point_layout.getchildat (i));} imageviews.get (
0). Setimageresource (R.mipmap.touched_holo);
private void Initview () {View v1=getlayoutinflater (). Inflate (R.layout.layout1,null);
View v2=getlayoutinflater (). Inflate (R.layout.layout2,null);
View v3=getlayoutinflater (). Inflate (R.layout.layout3,null);
Views.add (v1);
Views.add (v2);
Views.add (v3); //onpagechangelistener method, here does not do the concrete implementation @Override public void onpagescrolled (int position, float positionoffset, int Positionoffsetpixels) {}//Set the different state (picture) of the navigation Origin @Override public void onpageselected (int position) {ImageView PR after sliding to the view of the corresponding position
Eview = Imageviews.get (currimage);
Preview.setimageresource (R.mipmap.default_holo); ImageView Currview = Imageviews.get (POSition);
Currview.setimageresource (R.mipmap.touched_holo);
Currimage = position; The//onpagechangelistener method is not implemented here specifically @Override public void onpagescrollstatechanged (int state) {} class Myadapter Extend s Pageradapter {@Override public int getcount () {return views.size ():} @Override public boolean isviewfromobject (View V Iew, Object) {return view==object.} @Override public void Destroyitem (ViewGroup container, int position, Object o bject) {Container.removeview (Views.get (position));} @Override public Object instantiateitem (ViewGroup container, int
Position) {View v = views.get (position); Container.addview (v); Return v.}} }

At this point, the code needed to implement the Viewpager implementation sample is complete, of course, this is just the simplest feature of Viewpager, and later updates some Viewpager advanced usage, welcome the support of the small partners.

The above is a small set of Android to introduce the use of Viewpager to achieve screen page switching and page carousel effect, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.