Android Combat Simple Tutorial-the 48th Gun (App guide page effect implementation)

Source: Internet
Author: User

Often use the app's children's shoes will find that the first time to enter the app will have a guide page, which can put some app usage or other information, etc., below we look at how to achieve this function, to increase the experience of the app.

One, custom control inheritance ViewGroup:
Package Com.genius.scroll;import Android.content.context;import Android.content.intent;import Android.content.sharedpreferences;import Android.util.attributeset;import Android.util.log;import Android.view.motionevent;import Android.view.velocitytracker;import Android.view.view;import Android.view.viewgroup;import Android.widget.scroller;import Com.genius.demo.mainactivity;public Class Myscrolllayout extends ViewGroup {private static final String TAG = "Myscrolllayout";/** used to judge the swing gesture **/private Velocitytrack ER mvelocitytracker;private static final int snap_velocity = 600;/** Slide Controller **/private Scroller mscroller;private int mcurs  creen;private int mdefaultscreen = 0;private float mlastmotionx;/** current page **/private int currentpage;/** total page number **/private int Pagesize;private Context mcontext;//Contextual object private Onviewchangelistener monviewchangelistener;//view scrolling listener/** Does the callout jump to the main interface? **/private boolean go_main = False;private sharedpreferences preferences;public myscrolllayout (Context Context) {Super (conteXT); This.mcontext = Context;init (context);} Public Myscrolllayout (context context, AttributeSet Attrs) {Super (context, attrs); This.mcontext = Context;init (context );} Public Myscrolllayout (context context, AttributeSet attrs, int defstyle) {Super (context, attrs, defstyle); this.mcontext = Context;init (context);} /** * Gets the current page number * * @param page */public void setposition (int page) {if (page > 0) {currentpage = page;}} /** * Get Total pages * * @param size */public void setpagesize (int size) {pagesize = size;} private void init (context context) {Mcurscreen = Mdefaultscreen;mscroller = new Scroller (context);} /** * Call Scenario: The parameter description is called when the view is set to its child's size and position: parameter one: View has a new size or position; parameter two: relative to the left position of the parent view; * Parameter three: relative to the top position of the parent view; Parameter four: The right position relative to the parent view; parameter five: the bottom position relative to the parent view. */@Overrideprotected void OnLayout (Boolean changed, int l, int t, int r, int b) {if (changed) {//If there is a new dimension or position int Childleft = 0;final int childCount = Getchildcount ();//Returns the total number of child View for (int i = 0; i < ChildCount; i++) {//Traverse child viewfinal View Chil DView = GetchilDAt (i); if (childview.getvisibility ()! = View.gone) {//Childview.getmeasuredwidth () The width of the view that is obtained after the measurement of the content on the view, The premise is that you have to adjust the measure (0,0) in the parent's//OnLayout () method or in the OnDraw () method of the view;(the value of the measure//parameters you can define yourself), or you get the results and getwidth () The resulting result is a final int childwidth = Childview.getmeasuredwidth ();//parameter (relative to the left, top, right, and bottom position of the parent layout) childview.layout (childleft, 0, Childleft + childwidth,childview.getmeasuredheight ()); Childleft + = Childwidth;}}} /** * Indicates the space available to the control and the metadata about the space description. */@Overrideprotected void onmeasure (int widthmeasurespec, int heightmeasurespec) {super.onmeasure (Widthmeasurespec, HEIGHTMEASURESPEC);//Measurespec encapsulates the layout requirements that the parent layout passes to the child layout, each Measurespec represents a set of requirements for width and height. A measurespec consists of the size and pattern of the final int width = measurespec.getsize (widthmeasurespec);//extract the size value from the measured value provided final int widthmode = Measurespec.getmode (WIDTHMEASURESPEC);//based on the provided measurement value (format) extraction mode (there are three modes) LOG.D (TAG, "onmeasure width:" + width + "Widthmode:" + Widthmode); final int count = Getchildcount ();//Gets the total number of child views for (int i = 0; i < count; i++) {//Call Child view Getchildat (i). Measure (W IdthmeAsurespec, Heightmeasurespec);} ScrollTo (mcurscreen * width, 0);} public void Snaptodestination () {final int screenwidth = GetWidth (); final int destscreen = (GETSCROLLX () + SCREENWIDTH/2 )/Screenwidth;snaptoscreen (Destscreen);} public void Snaptoscreen (int whichscreen) {//Get a valid page layout Whichscreen = Math.max (0, Math.min (Whichscreen, Getchildcount ()- 1)); if (GETSCROLLX ()! = (Whichscreen * getwidth ())) {final int delta = whichscreen * getwidth ()-GETSCROLLX (); MSCROLLER.S Tartscroll (GETSCROLLX (), 0, Delta, 0,math.abs (Delta) * 2); mcurscreen = Whichscreen;invalidate (); Redraw layout if (Monviewchangelistener! = null) {Monviewchangelistener.onviewchange (Mcurscreen);}}} The/** * View Draw process is called */@Overridepublic void Computescroll () {if (Mscroller.computescrolloffset ()) {///If it returns True, Indicates that the animation has not finished Scrollto (Mscroller.getcurrx (), Mscroller.getcurry ());//produces a smooth animation effect, depending on the current offset, one point per scroll postinvalidate ();// Also need to refresh the view at this time, otherwise the effect may have error} else {//if return false, indicating Startscroll completed log.i (TAG, "Scoller has finished");}} @Overridepublic BoOlean Ontouchevent (Motionevent event) {Final int action = Event.getaction (); final float x = Event.getx (); final float y = E Vent.gety (); LOG.D (TAG, "x:" + x + "y:" + y); float oldx = 0;switch (action) {Case MOTIONEVENT.ACTION_DOWN:OLDX = event.getrawx (); LOG.I ("", "ontouchevent action_down"); if (Mvelocitytracker = = null) {Mvelocitytracker = Velocitytracker.obtain (); Mvelocitytracker.addmovement (event);} if (!mscroller.isfinished ()) {mscroller.abortanimation ();}  Mlastmotionx = x;break;case MotionEvent.ACTION_MOVE:int deltax = (int) (mlastmotionx-x); float newx = Event.getrawx ();/** * Last page Jump */if (Newx-oldx > 3) {if (currentpage = = pagesize-1 &&!go_main) {go_main = True;preferences = M Context.getsharedpreferences ("setting", 0); Sharedpreferences.editor Editor = Preferences.edit (); Editor.putboolean ("IsOpen", true); Editor.commit (); Intent Intent = new Intent (); Intent.setclass (Mcontext, mainactivity.class);//Jump to the first page; mcontext.startactivity (intent);}} if (Iscanmove (deltax)) {if (mVeLocitytracker = null) {mvelocitytracker.addmovement (event);} Mlastmotionx = X;scrollby (deltax, 0);} Break;case MotionEvent.ACTION_UP:int Velocityx = 0;if (Mvelocitytracker! = null) {mvelocitytracker.addmovement (event); Mvelocitytracker.computecurrentvelocity (+); Velocityx = (int) mvelocitytracker.getxvelocity ();} if (Velocityx > snap_velocity && mcurscreen > 0) {//move to the left LOG.E (TAG, "snap"); Snaptoscreen (mCurScreen-1 );} else if (Velocityx <-snap_velocity&& Mcurscreen < Getchildcount ()-1) {//move to the right log.e (TAG, "snap"); SNA Ptoscreen (Mcurscreen + 1);} else {snaptodestination ();} if (mvelocitytracker! = null) {mvelocitytracker.recycle (); mvelocitytracker = null;} break;} return true;} Private Boolean iscanmove (int deltax) {if (GETSCROLLX () <= 0 && deltax < 0) {return false;} if (Getscrollx () >= (Getchildcount ()-1) * getwidth () && deltax > 0) {return false;} return true;} public void Setonviewchangelistener (Onviewchangelistener listenER) {monviewchangelistener = listener;} **//* Determine whether to open index//* @return//*///private Boolean Isopean () {////}}
Second, define the interface
Package Com.genius.scroll;public interface Onviewchangelistener {public void onviewchange (int view);

Iii. creating an instance 1. Create Viewpageradapter.java:
Package Com.genius.demo;import Java.util.list;import Android.os.parcelable;import Android.support.v4.view.pageradapter;import Android.support.v4.view.viewpager;import android.view.View;/** * Viewpgageadapter Adapter * @author Yayun * */public class Viewpageadapter extends Pageradapter {list<view> mviewlist;pub Lic Viewpageadapter (list<view> viewlist) {mviewlist = viewlist;} @Overridepublic int GetCount () {if (mviewlist! = null) {return mviewlist.size ();} return 0;} @Overridepublic Object Instantiateitem (view view, int index) {(Viewpager) view. AddView (Mviewlist.get (index), 0); Return Mviewlist.get (index);} @Overridepublic void Destroyitem (view view, int position, Object arg2) {(Viewpager) view. Removeview (Mviewlist.get ( position));} @Overridepublic void Finishupdate (view arg0) {} @Overridepublic Boolean isviewfromobject (view view, Object obj) {return (V Iew = = obj);} @Overridepublic void Restorestate (parcelable arg0, ClassLoader arg1) {} @Overridepublic parcelable saveState () {return Null;} @Overridepublic void Startupdate (View arg0) {}}

2. Create Switchviewdemoactivity.java:
Package Com.genius.demo;import Android.app.activity;import Android.os.bundle;import android.view.view;import Android.view.view.onclicklistener;import Android.widget.imageview;import Android.widget.linearlayout;import Com.genius.scroll.myscrolllayout;import Com.genius.scroll.onviewchangelistener;public Class Switchviewdemoactivity extends Activity Implementsonviewchangelistener, Onclicklistener {private myscrolllayout Mscrolllayout;private imageview[] mimageviews;private int mviewcount;private int mcursel;/** Activity Object **/public Static Activity my_activity; @Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (R.layout.main); My_activity = This;init ();} private void Init () {mscrolllayout = (myscrolllayout) Findviewbyid (r.id.scrolllayout); LinearLayout linearlayout = (linearlayout) Findviewbyid (r.id.llayout); mviewcount = Mscrolllayout.getchildcount (); Mimageviews = new Imageview[mviewcount];for (int i = 0; i < Mviewcount; i++) {MimagevIews[i] = (ImageView) linearlayout.getchildat (i); mimageviews[i].setenabled (true); Mimageviews[i]. Setonclicklistener (this); Mimageviews[i].settag (i);} Mscrolllayout.setpagesize (mimageviews.length); Mcursel = 0;mimageviews[mcursel].setenabled (false); Mscrolllayout.setonviewchangelistener (this);} private void Setcurpoint (int index) {if (Index < 0 | | Index > MVIEWCOUNT-1 | | mcursel = = index) {return;} Mimageviews[mcursel].setenabled (True); mimageviews[index].setenabled (false); mscrolllayout.setposition (index); Mcursel = index;} @Overridepublic void Onviewchange (int view) {setcurpoint (view);} @Overridepublic void OnClick (View v) {int pos = (Integer) (V.gettag ()); Setcurpoint (POS); Mscrolllayout.snaptoscreen (pos );}}

3. layout file:
<?xml version= "1.0" encoding= "Utf-8"?> <relativelayout android:layout_width= "Fill_parent" Android:layout_ height= "Fill_parent" android:id= "@+id/touch" xmlns:android= "Http://schemas.android.com/apk/res/android" > & Lt;com.genius.scroll.myscrolllayout xmlns:android= "http://schemas.android.com/apk/res/android" android:id= "@+id/       Scrolllayout "android:layout_width=" fill_parent "android:layout_height=" fill_parent "> <FrameLayout android:background= "@drawable/guide01" android:layout_width= "fill_parent" android:layout_height= "Fill_pare NT "> </FrameLayout> <framelayout android:background=" @drawable/guide02 "Android:layout_wi Dth= "Fill_parent" android:layout_height= "fill_parent" > </FrameLayout> <framelayout Android          oid:background= "@drawable/guide03" android:layout_width= "fill_parent" android:layout_height= "Fill_parent" > </FrameLayout>       <framelayout android:background= "@drawable/guide04" android:layout_width= "Fill_parent" Android:la       yout_height= "Fill_parent" > </FrameLayout> <framelayout android:background= "@drawable/guide05"           Android:layout_width= "Fill_parent" android:layout_height= "fill_parent" > </FrameLayout> </com.genius.scroll.MyScrollLayout> <linearlayout android:orientation= "Horizontal" android:id= "@+id/l Layout "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "android:layout_marginbottom=" 24.0dip "android:layout_alignparentbottom=" true "android:layout_centerhorizontal=" true "> <imagevi EW android:clickable= "true" android:padding= "15.0dip" android:layout_gravity= "center_vertical" Android:layout_ Width= "Wrap_content" android:layout_height= "wrap_content" android:src= "@drawable/guide_round"/> <ImageView A Ndroid:clickable= "true" Android:padding= "15.0dip" android:layout_gravity= "center_vertical" android:layout_width= "Wrap_content" Android:layout_ height= "Wrap_content" android:src= "@drawable/guide_round"/> <imageview android:clickable= "true" Android:pad ding= "15.0dip" android:layout_gravity= "center_vertical" android:layout_width= "Wrap_content" android:layout_height = "Wrap_content" android:src= "@drawable/guide_round"/> <imageview android:clickable= "true" android:padding= " 15.0dip "android:layout_gravity=" center_vertical "android:layout_width=" wrap_content "android:layout_height=" wrap _content "android:src=" @drawable/guide_round "/> <imageview android:clickable=" true "android:padding=" 15.0di P "android:layout_gravity=" center_vertical "android:layout_width=" wrap_content "android:layout_height=" Wrap_ Content "android:src=" @drawable/guide_round "/> </LinearLayout> </RelativeLayout>

Four, running example:


like friends please pay attention to me! Source Download

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Combat Simple Tutorial-the 48th Gun (App guide page effect implementation)

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.