SurfaceView and surfaceview
Package com. example. test; import android. content. context; import android. graphics. canvas; import android. graphics. color; import android. graphics. paint; import android. view. motionEvent; import android. view. surfaceHolder; import android. view. surfaceHolder. callback; import android. view. surfaceView;/*** inherits SurfaceView * to implement SurfaceHolder. callback: Creates a SurfaceHolder for * used by SurfaceHolder, and addCallback. SurfaceView has Su. RfaceHolder control */public class MySurfaceView extends SurfaceView implements Callback, Runnable {// SurfaceView BASIC private SurfaceHolder sfh; // SurfaceViewprivate Paint p; private Canvas c; // Thread private Thread t; private boolean flag; // data private int screenW, screenH; private int xx = 100, yy = 100; public MySurfaceView (Context context) {super (context); sfh = this. getHolder (); sfh. addCallback (this); p = new Pain T (); p. setColor (Color. RED) ;}@ Overridepublic boolean onTouchEvent (MotionEvent event) {xx = (int) event. getX (); yy = (int) event. getY (); return true;} public void myDraw () {try {// when SurfaceView is not editable or has not been created, nullc = sfh is returned. lockCanvas (); if (c! = Null) {c. drawColor (Color. GREEN); // screen c. drawText ("me", xx, yy, p); // draw} catch (Exception e) {} finally {if (c! = Null) {sfh. unlockCanvasAndPost (c) ;}}// game logic public void logic () {}@ Overridepublic void surfaceCreated (SurfaceHolder holder) {screenW = this. getWidth (); screenH = this. getHeight (); // the initialization and startup of the Thread are all written in create. flag = true; t = new Thread (this); t. start () ;}@ Overridepublic void surfaceChanged (SurfaceHolder holder, int format, int width, int height) {}@ Overridepublic void surfaceDestroyed (SurfaceHolder holder) {f Lag = false ;}@ Overridepublic void run () {while (flag) {// The Screen flushing time remains consistent. // generally, 10 ~ About 20 frames // 20 frames per second: 1000 ms/20 = 50 ms long start = System per frame. currentTimeMillis (); myDraw (); logic (); long end = System. currentTimeMillis (); try {if (end-start <50) {Thread. sleep (50-(end-start);} catch (InterruptedException e) {e. printStackTrace ();}}}}
SurfaceView lifecycle:
How does android rewrite the three functions when surfaceview is created?
Right-click -- Source --- override/implement methods and find the function to be reloaded.
These two functions are respectively used to create, change, and destroy the Canvas through the open management Canvas in SurfaceHolder.
LockCanvas is used before drawing, and unlockCanvasAndPost is used after drawing.
How can I add my surfaceview to the xml layout for android development?
That's a custom parameter. You need to write it in styleable. xml. After being defined in the xml layout, the parameters are parsed in SurfaceView.