[Mobile development] Android custom Control series six: Custom ViewGroup (i) Achieve viewpager effect

Source: Internet
Author: User

Today we start a new Android custom component journey, the following is how to customize a viewgoup, before we have already learned the basic way to write a custom view through several blog posts, if you do not know the students, you can see the following column article: Android custom control.

This is also an example of how to customize a ViewGroup, the ultimate goal is to implement a class Viewpager function ViewGroup.


Let's start by looking at the final effect:




for the system ViewGroup we are already very familiar with, the most commonly used linearlayout and relativelayout almost every day to deal with, below we will see, how to step by step to achieve it:


first of all, of course, the most common new Android project, and then create a new class inside inherit from ViewGroup, here we call this class Myviewpager.

After implementing the inheritance ViewGroup, we will find that we need to implement a method that is not implemented: the first is a two-parameter constructor, which is used to generate the corresponding Component object for the XML layout file, and the second is onlayout, which we should not be unfamiliar with, As mentioned in the previous few custom view posts, the OnLayout method actually specifies the location of the component, where it is actually given to ViewGroup's child view to determine the location. So here's what we need to think about, and what kind of positional relationship we viewgroup want to achieve:

Added that we have 6 pictures to show, if you want to achieve viewpager effect, you need to display a picture at a time, and then swipe left and right, you can display before and after the other pictures (if there are pictures before and after); To achieve such an effect, What we should do in the OnLayout method is to arrange our sub view (ImageView object for the picture) and see the following picture:



As shown in the OnLayout method, the coordinates origin of the Android system is located in the top left corner of the phone screen, the square of x and Y is right and down, and for the case where the Viewpager effect requires horizontal sliding, our sub view (ImageView) It should be arranged horizontally in the X-y coordinate system as shown in the image above, so that the left and right images can be displayed on the phone screen when our fingers are sliding horizontally. So here, the work we need to do is:


1. Get all the sub-view.
2, these sub-view according to want to display the order, horizontal arrangement, each sub-view of the upper left corner and the front and back of the sub-view of the upper left corner of the horizontal distance is the width of a phone screen, the vertical direction of all sub-view flat.


Implemented in code, as follows:

@Override/** * Layout of the sub-view to determine the location of the child view * @param changed represents the OnLayout method, the current layout has not changed, if it has changed to true, otherwise false * @param int l, int t, int r, int b represents the current view, which is our myviewpager, relative to the location of its parent view, where we are arranging our own sub-view * These parameters are basically nothing */protected void onlay Out (Boolean changed, int l, int t, int r, int b) {//① First gets all the sub-viewfor (int i = 0; i < Getchildcount (); i++) {View view = Getchildat (i);//Get the sub-view//② of the following table for I to arrange the child view, in fact, it is necessary to call the layout method of sub-view, four parameters corresponding to left, top, right, lower view.layout (i * getwidth (), 0, GetWidth () * (i + 1), getheight ());}}


The above code in the View.layout method corresponding to the left, top, right, and the next four parameters corresponding to the current sub-view of the left, top, right, bottom up four edges, corresponding to the parent ViewGroup is our custom viewgroup distance, so arranged well, The effect is not the effect, but the location of the No. 0 ImageView on the phone screen, while the other imageview are arranged on the right.


second, define touch events so that we can use gestures to slide the sub-view that we previously arranged for the OnLayout method to display.

Here we must use the Ontouchevent method, This method is the touch event passed through the Dispatchtouchevent method and the Onintercepttouchevent method will first pass the touch event to the Ontouchevent method, with regard to the passing mechanism of the touch event, will be covered in the next article. As we have done before, we are using the switch statement directly in Ontouchevent to perform different processing in the three states of Action_down,action_move and ACTION_UP. Here we first use one of the classes provided by Android to handle:gesturedetector. gesturedetector can be used to receive an event and then handle the different types of events accordingly: we simply use gesturedetector. Ontouchevent (event); The key here is the method to be implemented when creating this gesturedetector object:


detector = new Gesturedetector (context, new Ongesturelistener () {@Override/** * There is a finger lifted when the callback */public Boolean Onsingletap Up (Motionevent e) {//TODO auto-generated method Stubreturn false;} @Override/** * */public void onshowpress (Motionevent e) {//TODO auto-generated method stub} When there is a finger tapping the screen @Override/** * When there is a hand The callback */public Boolean onscroll (motionevent E1, motionevent e2,float Distancex, float Distancey) {return false;} when sliding on the screen  @Override/** * callback */public void onlongpress (Motionevent e) {//TODO auto-generated method stub} @Override/** * When a finger is long pressed on the screen Quick Swipe Callback */public Boolean onfling (motionevent E1, motionevent e2,float Velocityx, float velocityy) {//TODO Auto-generat Ed method Stubreturn false;} @Override/** * Press the callback method */public Boolean Ondown (motionevent e) {//TODO auto-generated method Stubreturn false;}});



It is not difficult to see the gesturedetector of the classification of the event to resolve a number of ways ... Here we only care about sliding, so just pay attention to the Onscroll method: public boolean onscroll (motionevent E1, motionevent e2,float Distancex, float Distancey), four parameters, E1 represents the first Action_down event that triggered this event, E2 represents the Action_move event that triggered the event, Distancex, The Distancey represents the distance from the last call to the onscroll call to the onscroll call in the X and y directions. What needs to be noted here is that the positive and negative values of Distancex and Distancey are not as positive or negative as the coordinates shown in the previous viewgroup, but the left slide value is Distancex positive and the right sliding value is Distancex negative.


After figuring out the meaning of the parameters, the next thing to do is to onscroll the sub-view to slide up ~ Here is a grand introduction of a method: public void Scrollby (int x, int y), where we call this method, will Distancex pass in, The second parameter is set to 0 (because there is no need to slide in the Y direction) to achieve our sliding purpose: Scrollby ((int) Distancex, 0); Inside the Scrollby method, the Scrollto method is actually overridden, The Scrollto method is to move the datum point of the current view of the control that invokes him to a coordinate point, and for this is our viewgroup, imagine if the datum point x coordinate moves to the negative screen width, then the realistic sub view will not become 1th number:


@Override/** * Callback */public Boolean onscroll (motionevent E1, motionevent e2,float Distancex, float distancey) When a finger is sliding on the screen {//System.out.println ("" + Distancex),///Distancex is positive, moving to the left, negative, the method of moving the screen to the right Scrollby, it is important that this method calls the Onscrollchanged method And refreshes the view/** * DX represents the distance moving in the x direction, and Dy represents the distance traveled in the y direction. If you move upward toward the axis, the value is positive, and negative *///Scrollby internally actually overrides the Scrollto method, Scrollto is to move the datum point of the current view to a coordinate point Scrollby ((int) Distancex, 0); return false;}



Well, at this point, we're ready to look at the effect; we'll write our custom viewgroup in the layout file:


<com.example.myviewpager.ui.myviewpager        android:id= "@+id/my_view_pager"        android:layout_width= "Fill_ Parent "        android:layout_height=" Fill_parent "/>



Then in the mainactivity, the Myviewpager object is created Myviewpager, the resource files of the picture, are placed in the drawable directory, Then loop through the Myviewpager.addview method and add a sub-view to our ViewGroup:


package Com.example.myviewpager;import Android.app.activity;import Android.os.bundle;import Android.view.Window;import Android.widget.imageview;import Com.example.myviewpager.ui.myviewpager;public class MainActivity extends Activity { Private Myviewpager myviewpager;//image resource ID array private int[] ids = new int[] {r.drawable.a1, r.drawable.a2,r.drawable.a3, R.D RAWABLE.A4, R.drawable.a5, r.drawable.a6}; @Overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate);//Achieve Untitled Effect requestwindowfeature (Window.feature_no_title); SetContentView ( R.layout.activity_main); Myviewpager = (Myviewpager) Findviewbyid (R.id.my_view_pager); for (int i = 0; i < ids.length; I + +) {ImageView ImageView = new ImageView (this); Imageview.setbackgroundresource (Ids[i]);// Add ImageView to Custom Viewgroupmyviewpager.addview (ImageView);}} 

Well, so far, we can first look at the stage effect ~ ^_^:



It looks good, the basic sliding function has been implemented, but there are still some problems:

1, in the first picture and the last picture when the display continues to slide, will show blank content, and stay

2, when lifting the finger, will not automatically revert to display a full picture status


three, solve the two problems: blank page display, lifting the finger auto Recovery Select Show full picture
1, blank page display problems

The solution is to use an integer value CurrentID to represent the current slide to which position, the first open when the position is 0, if the page to the right slide, and reached the condition of sliding to the next page, then CurrentID + 1, if it is going to slide to the previous page, CurrentID-1, of course, the value of CurrentID is also a range, that is [0,getchildcount ()-1], if currentid<0, we let it equals 0, if currentid>= Getchildcount, we let it be equal to getChildCount-1, and then slide to the corresponding CurrentID position to stop, this solves the


2. When lifting the finger, let the picture show the problem of auto-homing.

The solution is to lift the finger when the distance from the beginning of the finger when the sliding distance, if it is to the right or to the left is greater than the screen distance of 1/2, then to the right or left to slide the display of a picture, if less than 1/2, then slide back to the page displayed before. Here involves pressing and lifting up to two actions, we can continue to add the switch judgment condition in Myviewpager's Ontouchevent method, to obtain the corresponding value to judge the sliding condition, mainly is to add the content in the Ontouchevent method, we take a look at:

/** * Down event x-coordinate */private int firstx;private int currentid;//The ID of the currently displayed picture, starting with 0, the maximum value is Getchildcount () -1@overridepublic Boolean ontouchevent (Motionevent event) {super.ontouchevent (event);//Use tools to parse the touch event detector.ontouchevent. Switch (event.getaction ()) {Case MotionEvent.ACTION_DOWN:firstX = (int) event.getx (); Break;case Motionevent.action_ Move:break;case MotionEvent.ACTION_UP:int tmpid = 0; System.out.println ("currentid=" + currentid);//swipe right over screen 1/2, current ID should be -1if (Event.getx ()-FIRSTX > GetWidth ()/2) {T MpId = currentId-1;} else if (Firstx-event.getx () > GetWidth ()/2) {tmpid = CurrentID + 1;} else {tmpid = CurrentID;} System.out.println ("currentid=" + currentid);//Three The efficiency of the mesh operator is much higher than if else efficiency. int childCount = Getchildcount (); CurrentID = Tmpid < 0? 0: ((tmpid > ChildCount-1) childCount-1: tmpid); ScrollTo (Currentid*getwidth (), 0); break;default:break;} Consume this event return true;}


after the above changes, we will look at the effect:


After the above changes, found that the two previous problems have been solved, but it is still a bit uncomfortable to see is not ... Let go and then bounce back, the user experience is not very good ah. So here we have to add a sliding delay mechanism after letting go, let it slide more and more slowly, and finally slide to the position we want.


Four, let go the implementation of sliding delay effect:

For this piece, Android is actually also have API to use, here we first to implement to see.

Here the core idea, or to call the Scrollto method, just to pick up the finger after the first to get the distance to slide, and then in the specified time to smooth the speed up the distance can be, so we need to call the Scrollto method several times to move to a different point in the various locations.


We write a class distanceprovider ourselves to implement the above functions. We first get the distance we want to move, and then we pass the distance parameter into the Distanceprovider start slide method Startscroll.


First the previous scrollto (CurrentID * getwidth (), 0); Comment out the sentence, write a method: Movetodest ();


/** * Move to a reasonable position method */private void Movetodest () {/** * move start to end distance */int distance = CurrentID * GetWidth ()-GETSCROLLX ();/** * Within a period of time, the smooth movement of this distance *///open calculated offset Distanceprovider.startscroll (getscrollx (), 0, distance, 0); invalidate ();// Invalidate causes the execution of OnDraw and Computescroll methods}




Here's a look at how the Distanceprovider class is written, and here's a point of knowledge that in the Invalidate method, in addition to calling the OnDraw method, a method computescroll is called, This method is not implemented in the parent class, is actually provided to developers to use, we can rewrite the Computescroll method, in which to determine whether the automatic sliding end, if not end, get the latest sliding position, and refresh the view again call invalidate method, The Invalidate method of this call will then call the Computescroll method until the auto-slide is complete.



For the Distanceproviderl class, it is implemented as follows:


Package Com.example.myviewpager.utils;import android.content.context;import android.os.systemclock;/** * Tool class for calculating displacement distances * * @author Alex * */public class Distanceprovider {private int startx;private int starty;private int distancex;private int distancey;/** * Time to start the animation */private long starttime;/** * Determines if the animation is still being executed, true is stopped, False indicates that */private Boolean isfinish is still running; /** * Default run time, millisecond value, 300 ms */private Long duration;/** * Current x value */private long currentx;private long Currenty;public long GetC Urrentx () {return currentx;} public void Setcurrentx (long currentx) {this.currentx = CurrentX;} Public Distanceprovider (Context context) {isfinish = false;} /** * Start Moving * * @param startX * x Start coordinates * @param starty * y start coordinates * @param Distancex * x direction to Distance traveled * @param distancey * y direction to move the distance */public void startscroll (int startX, int starty, int distancex, int dista Ncey) {this.startx = Startx;this.starty = Starty;this.distancex = Distancex;this.distancey = DistanceY;this.startTime = SYstemclock.uptimemillis ();//We'll set the slide duration to 300 milliseconds this.duration = 300;this.isfinish = false;} /** * Calculates the current running status * * @return true: Indicates that the run ends false: indicates that the */public boolean computescrolloffset () {if (isfinish) {return ISFI is still running Nish;} Calculate how long the slide has run long passtime = Systemclock.uptimemillis ()-Starttime;if (Passtime < duration) {CurrentX = StartX + di Stancex * Passtime/duration;currenty = starty + Distancex * passtime/duration;} else {CurrentX = StartX + distancex;currenty = starty + Distancey;isfinish = true;} return false;}}




For the Computescroll method in custom ViewGroup:


@Overridepublic void Computescroll () {//Super.computescroll ();//Calculates the sliding offset if (!distanceprovider.computescrolloffset () {int newx = (int) distanceprovider.getcurrentx (); ScrollTo (newx, 0);//Refresh invalidate again ();}}



After this change, we basically realized the function of ViewGroup.



The next article will be based on the study of the Android touch event transmission mechanism , please pay attention! Thank you!


[Mobile development] Android custom Control series six: Custom ViewGroup (i) Achieve viewpager effect

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.