An implementation of sliding effect based on Android novel reader

Source: Internet
Author: User

Read the novel all know the novel Reader page has a good variety of effects, such as simulation page, sliding page, and so on. For some reason, suddenly want to write a simple point of sliding page flipping effect. There is no intention to write here, I hope you can extrapolate according to this effect, write other effects. The picture won't go up.

Here is the code: you understand the Ontouch event can be

Package Com.example.testscroll.view;import Android.content.context;import Android.util.attributeset;import Android.view.motionevent;import Android.view.velocitytracker;import Android.view.view;import Android.view.viewconfiguration;import Android.view.viewgroup;import Android.widget.scroller;public Class Flipperlayout extends ViewGroup {private Scroller mscroller;private velocitytracker mvelocitytracker;private int Mvelocityvalue = 0;/** Agree whether this slip is valid distance */private int limitdistance = 0;private int screenwidth = 0;/** finger move Direction */private STA Tic Final int move_to_left = 0;private static final int move_to_right = 1;private static final int move_no_result = 2;/** Final touch result direction */private int mtouchresult = move_no_result;/** start direction */private int mdirection = move_no_result;/** Touch mode */pri vate static final int mode_none = 0;private static final int mode_move = 1;private int mmode = mode_none;/** sliding View */pri vate View Mscrollerview = null;/** top view (edge, invisible) */private View Currenttopview = null;/* * Displayed view, displayed on screen */private view Currentshowview = null;/** bottom View (invisible) */private View Currentbottomview = Null;public F Lipperlayout (Context context) {super (context); init (context);} Public Flipperlayout (context context, AttributeSet attrs, int defstyle) {Super (context, attrs, defstyle); init (context);} Public Flipperlayout (context context, AttributeSet Attrs) {Super (context, attrs); init (context);} private void init (context context) {Mscroller = new Scroller (context); screenwidth = Context.getresources (). Getdisplaymetrics (). widthpixels;limitdistance = SCREENWIDTH/3;} /*** * * @param listener * @param currentbottomview * Lowest view, initial status not seen * @param currentshowview * Viewing view * @param curr Enttopview * Topmost View, slide out of screen when initializing */public void Initflipperviews (Touchlistener listener, view Currentbottomview, view Currentshowview, View currenttopview) {This.currentbottomview = Currentbottomview;this.currentshowview = Currentshowview;this.currenttopview = Currenttopview;settouchresultlistener (listener); aDdview (Currentbottomview); AddView (Currentshowview); AddView (Currenttopview);/** defaults to the top-most view sliding edge (for viewing the previous page) */ Currenttopview.scrollto (-screenwidth, 0);} @Overrideprotected void OnLayout (Boolean changed, int l, int t, int r, int b) {for (int i = 0; i < Getchildcount (); i++ {View child = Getchildat (i); int height = child.getmeasuredheight (); int width = Child.getmeasuredwidth (); Child.layout (0 , 0, width, height);}} @Overrideprotected void onmeasure (int widthmeasurespec, int heightmeasurespec) {super.onmeasure (Widthmeasurespec, HEIGHTMEASURESPEC); int width = measurespec.getsize (widthmeasurespec); int height = measurespec.getsize ( HEIGHTMEASURESPEC); setmeasureddimension (width, height); for (int i = 0; i < Getchildcount (); i++) {Getchildat (i). Measure (Widthmeasurespec, Heightmeasurespec);}} private int startX = 0; @Overridepublic boolean dispatchtouchevent (motionevent ev) {switch (ev.getaction ()) {case Motionev Ent. Action_down:if (!mscroller.isfinished ()) {break;} StartX = (int) ev.getx (); break;} RetUrn super.dispatchtouchevent (EV);} @SuppressWarnings ("Deprecation") @Overridepublic Boolean ontouchevent (Motionevent event) {Obtainvelocitytracker ( event), switch (Event.getaction ()) {Case MotionEvent.ACTION_MOVE:if (!mscroller.isfinished ()) {return Super.ontouchevent (event);} if (StartX = = 0) {StartX = (int) event.getx ();} final int distance = StartX-(int) event.getx (); if (mdirection = = Move_no_result) {if (Mlistener.whetherhasnextpage () &am  p;& Distance > 0) {mdirection = Move_to_left;} else if (Mlistener.whetherhaspreviouspage () && Distance < 0) {mdirection = Move_to_right;}} if (Mmode = = mode_none&& (mdirection = = Move_to_left && mlistener.whetherhasnextpage ()) | | (mdirection = = Move_to_right && mlistener.whetherhaspreviouspage ()))) {mmode = Mode_move;} if (Mmode = = Mode_move) {if (mdirection = = Move_to_left && distance <= 0) | | (mdirection = = move_to_right && distance >= 0)) {mmode = Mode_none;}} if (mdirection! = Move_no_rEsult) {if (mdirection = = Move_to_left) {if (Mscrollerview! = Currentshowview) {Mscrollerview = Currentshowview;}} else {I F (mscrollerview! = Currenttopview) {Mscrollerview = Currenttopview;}} if (Mmode = = Mode_move) {mvelocitytracker.computecurrentvelocity (viewconfiguration.getmaximumflingvelocity ()) if (mdirection = = Move_to_left) {mscrollerview.scrollto (distance, 0);} else {Mscrollerview.scrollto (screenwidth + Distance, 0);}} else {final int scrollx = MSCROLLERVIEW.GETSCROLLX (); if (mdirection = = Move_to_left && scrollx! = 0 && MLi Stener.whetherhasnextpage ()) {mscrollerview.scrollto (0, 0);} else if (mdirection = = Move_to_right && Mlistener.whetherhaspreviouspage () && screenwidth! = Math.Abs (SCROLLX)) {Mscrollerview.scrollto (- ScreenWidth, 0);}} Break;case MotionEvent.ACTION_UP:if (Mscrollerview = = null) {return super.ontouchevent (event);} Final int scrollx = MSCROLLERVIEW.GETSCROLLX (), mvelocityvalue = (int) mvelocitytracker.getxvelocity ();//Scroll LeftPositive, right negative (), (StartX + dx) value if 0, that is, reset/* * Android.widget.Scroller.startScroll (int startX, int starty, int * dx, int dy, int dura tion) */int time = 500;if (Mmode = = Mode_move && mdirection = move_to_left) {if (Scrollx > Limitdistance | | m Velocityvalue <-time) {//the finger moves to the left, can turn the screen Mtouchresult = move_to_left;if (Mvelocityvalue <-time) {time = 200;} Mscroller.startscroll (scrollx, 0, SCREENWIDTH-SCROLLX, 0, time);} else {Mtouchresult = Move_no_result;mscroller.startscroll (scrollx, 0,-SCROLLX, 0, time);}} else if (Mmode = = Mode_move && mdirection = = move_to_right) {if (SCREENWIDTH-SCROLLX) > Limitdistance | | mVe Locityvalue > Time) {//the finger moves to the right, can turn the screen Mtouchresult = move_to_right;if (Mvelocityvalue > Time) {time = 250;} Mscroller.startscroll (scrollx, 0,-SCROLLX, 0, time);} else {Mtouchresult = Move_no_result;mscroller.startscroll (scrollx, 0, SCREENWIDTH-SCROLLX, 0, time);}} Resetvariables ();p ostinvalidate (); break;} return true;} private void Resetvariables () {Mdirection = Move_no_result;mmode = Mode_none;startx = 0;releasevelocitytracker ();} Private Touchlistener mlistener;private void Settouchresultlistener (Touchlistener listener) {This.mlistener = Listener ;} @Overridepublic void Computescroll () {super.computescroll (); if (Mscroller.computescrolloffset ()) { Mscrollerview.scrollto (Mscroller.getcurrx (), Mscroller.getcurry ());p ostinvalidate (); else if (mscroller.isfinished () && Mlistener! = NULL && Mtouchresult! = Move_no_result) {if (Mtouchresult = = Move_to_left) {if (Currenttopview! = null) {Removeview (Currenttopview);} Currenttopview = Mscrollerview;currentshowview = Currentbottomview;if (Mlistener.currentislastpage ()) {final View Newview = Mlistener.createview (mtouchresult); Currentbottomview = Newview;addview (newview, 0);} else {Currentbottomview = new View (GetContext ()); currentbottomview.setvisibility (View.gone); AddView ( Currentbottomview, 0);}} else {if (Currentbottomview! = null) {Removeview (Currentbottomview);} Currentbottomview= Currentshowview;currentshowview = Mscrollerview;if (Mlistener.currentisfirstpage ()) {final View NewView = Mlistener.createview (mtouchresult); Currenttopview = Newview;currenttopview.scrollto (-screenWidth, 0); AddView ( Currenttopview);} else {Currenttopview = new View (GetContext ()); Currenttopview.scrollto (-screenwidth, 0); currenttopview.setvisibility (View.gone); AddView (Currenttopview);}} Mtouchresult = Move_no_result;}} private void Obtainvelocitytracker (Motionevent event) {if (Mvelocitytracker = = null) {Mvelocitytracker = Velocitytracker . obtain ();} Mvelocitytracker.addmovement (event);} private void Releasevelocitytracker () {if (Mvelocitytracker! = null) {mvelocitytracker.recycle (); mvelocitytracker = null;}} /*** * For real-time callback Touch Event callback * * @author Freeson */public interface Touchlistener {/** finger swipe left to view next Chapter */final int move_to_left = 0 /** finger to the right, that is to see the previous chapter */final int move_to_right = 1;/** * Create a view * * @param direction * {@link move_to_) that hosts text Left,move_to_right} * @return */public View CReateview (final int direction);/*** * Whether the current page is the first page * * @return */public boolean currentisfirstpage ();/*** * is the last page of the current page * * @return */public boolean currentislastpage ();/** * Whether the current page has a previous page (used to determine the sliding nature) * * @return */public Boolean Whetherhaspreviouspag E ();/*** * Whether the current page has the next page (used to determine the sliding nature) * * @return */public boolean whetherhasnextpage ();}}

Activity test File:

Package Com.example.testscroll;import Java.io.bytearrayoutputstream;import Java.io.ioexception;import Java.io.inputstream;import Android.app.activity;import Android.content.res.assetmanager;import Android.os.Bundle; Import Android.os.handler;import Android.view.layoutinflater;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.textview;import Com.example.testscroll.view.flipperlayout;import Com.example.testscroll.view.flipperlayout.touchlistener;import Com.example.testscrollactivity.r;public class Mainactivity extends Activity implements Onclicklistener, Touchlistener  {Private String Text = "";p rivate int textlenght = 0;private static final int COUNT = 400;private int currenttopendindex = 0;private int currentshowendindex = 0;private int currentbottomendindex = 0;private Handler Handler = new Handler () {Publ IC void Handlemessage (Android.os.Message msg) {flipperlayout rootlayout = (flipperlayout) Findviewbyid (R.id.container) ; View Recoverview = LayoutinFlater.from (Mainactivity.this). Inflate (r.layout.view_new, NULL); View view1 = Layoutinflater.from (mainactivity.this). Inflate (r.layout.view_new, NULL); View view2 = Layoutinflater.from (mainactivity.this). Inflate (r.layout.view_new, null); Rootlayout.initflipperviews ( Mainactivity.this, View2, View1, recoverview); textlenght = Text.length (); SYSTEM.OUT.PRINTLN ("----textlenght----->" + textlenght); TextView TextView = (TextView) View1.findviewbyid (R.id.textview), if (Textlenght > COUNT) {textview.settext ( Text.subsequence (0, Count)); TextView = (TextView) View2.findviewbyid (R.id.textview); if (Textlenght > (Count < < 1)) {Textview.settext (Text.subsequence (count, Count * 2)); Currentshowendindex = Count;currentbottomendindex = COUNT << 1;} else {textview.settext (text.subsequence (COUNT, Textlenght)); Currentshowendindex = Textlenght;currentbottomendindex = Textlenght;}} else {textview.settext (text.subsequence (0, Textlenght)); currentshowendindex = Textlenght;currentbottomendindex = TexTlenght;};}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); new Readingthread (). Start ();}  @Overridepublic void OnClick (View v) {} @Overridepublic view CreateView (final int direction) {String txt = ""; if (direction = = Touchlistener.move_to_left) {currenttopendindex = currentshowendindex;final int nextindex = CurrentBottomEndIndex + C Ount;currentshowendindex = currentbottomendindex;if (Textlenght > Nextindex) {txt = text.substring ( Currentbottomendindex, nextindex); currentbottomendindex = Nextindex;} else {txt = text.substring (Currentbottomendindex, textlenght); currentbottomendindex = Textlenght;}} else {currentbottomendindex = Currentshowendindex;currentshowendindex = Currenttopendindex;currenttopendindex = Currenttopendindex-count;txt = text.substring (Currenttopendindex-count, currenttopendindex);} View view = Layoutinflater.from (this). Inflate (r.layout.view_new, NULL); TextView TextView = (textvieW) View.findviewbyid (R.id.textview); textview.settext (TXT); System.out.println ("-top->" + Currenttopendindex + "-show->" + Currentshowendindex + "--bottom-->" + Currentbottomendindex); return view;} @Overridepublic Boolean whetherhaspreviouspage () {return currentshowendindex > COUNT;} @Overridepublic Boolean whetherhasnextpage () {return currentshowendindex < textlenght;} @Overridepublic Boolean Currentisfirstpage () {Boolean should = Currenttopendindex > count;if (!should) { Currentbottomendindex = Currentshowendindex;currentshowendindex = Currenttopendindex;currenttopendindex = Currenttopendindex-count;} return should;} @Overridepublic Boolean Currentislastpage () {Boolean should = Currentbottomendindex < Textlenght;if (!should) { Currenttopendindex = currentshowendindex;final int nextindex = currentbottomendindex + Count;currentshowendindex = Currentbottomendindex;if (Textlenght > Nextindex) {currentbottomendindex = Nextindex;} else {currentbottomendindex = Textlenght;}}return should;} Private class Readingthread extends Thread {public void run () {Assetmanager am = getassets (); InputStream Response;try {res Ponse = Am.open ("Text.txt"), if (response! = null) {Bytearrayoutputstream BAOs = new Bytearrayoutputstream (); int i = -1;whi Le ((i = Response.read ())! =-1) {baos.write (i);} Text = new String (Baos.tobytearray (), "UTF-8"); Baos.close (); Response.close (); handler.sendemptymessage (0);}} catch (IOException e) {e.printstacktrace ();}}}}

XML layout file:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" match_parent "    android:layout_height=" match_parent "    android:o rientation= "Horizontal" >    <textview        android:id= "@+id/textview"        android:layout_width= "0DP"        android:layout_height= "match_parent"        android:layout_weight= "1.0"        android:background= "#666666"        android:gravity= "center"        android:text= "New View"        android:textcolor= "@android: Color/white"        Android:textsize= "16SP"        android:visibility= "visible"/>    <view        android:layout_width= "5DP"        android:layout_height= "match_parent"        android:background= "#FFFF00"        android:gravity= "center"        android:textsize= "25SP"        android:visibility= "visible"/></linearlayout>

Activity layout File:

<com.example.testscroll.view.flipperlayout xmlns:android= "Http://schemas.android.com/apk/res/android"    xmlns:tools= "Http://schemas.android.com/tools"    android:id= "@+id/container"    android:layout_width= "match _parent "    android:layout_height=" Match_parent "></com.example.testscroll.view.FlipperLayout>

Note: Why add a rate calculator above, in fact, just to recognize that this action is not a fast sliding action, even if the sliding distance is not 1/3 of the screen, but as long as the rate of satisfaction can be determined to change the slide is a page action.

Note: This is just one of the sliding effects, not including the logic of chapters in fiction. Although some rough, but there can be worth learning, if you have any good solution, you can discuss together.

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.