Mysurfaceview.java
Package Com.example.surfaceview;
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;
public class Mysurfaceview extends Surfaceview implements callback{
Private Surfaceholder SFH;
private paint paint;
private int textx=10,texty=10;
Public Mysurfaceview (Context context)
{
Super (context);
Sfh=this.getholder ();//control Surfaceview the size of the format is mainly used to monitor the status of Surfaceview
In fact, Surfaceview just saves the current view's pixel data and does not deal directly with Surfaceview when using Surfaceview
Instead, the Lockcanvas () function using Surfaceholder is controlled by Surfaceholder to obtain the Surfaceview
The Canvas object. Modify the data in the Surfaceview by drawing content on the canvas
Locakcanvas not only gets the canvas but also locks the captured canvas.
Sfh.addcallback (this);//incoming its listener interface instance: Complete monitoring of the Surfaceview
Paint=new Paint ();
Paint.setcolor (Color.White);
Setfocusable (TRUE);
}
@Override
public void surfacechanged (surfaceholder holder, int format, int width,
int height) {
TODO auto-generated Method Stub
}
@Override
public void surfacecreated (Surfaceholder holder) {
TODO auto-generated Method Stub
Mydraw ();
}
@Override
public void surfacedestroyed (Surfaceholder holder) {
TODO auto-generated Method Stub
}
public void Mydraw ()
{
Canvas Canvas=sfh.lockcanvas ();
Canvas.drawrect (0, 0,this.getwidth (), This.getheight (), paint);//the first method draws a rectangle of the same size as the phone screen
Canvas.drawcolor (Color.Black);//the second Methos draw color fills entire screen
Canvas.drawrgb (0,0,0);//the third method Drawing color fills the entire screen
Canvas.drawtext ("Game", Textx, texty, paint);
Sfh.unlockcanvasandpost (canvas);
}
public boolean ontouchevent (Motionevent event)
{
textx= (int) event.getx ();
texty= (int) event.gety ();
Mydraw ();
Invalidate ();
return true;
}
}
Mainactivity.java as follows:
Package Com.example.surfaceview;
Import Android.os.Bundle;
Import android.app.Activity;
Import Android.view.Menu;
public class Mainactivity extends Activity {
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (New Mysurfaceview (this));
}
@Override
public boolean Oncreateoptionsmenu (Menu menu) {
Inflate the menu; This adds items to the action bar if it is present.
Getmenuinflater (). Inflate (R.menu.main, menu);
return true;
}
}
This article is from the "Hagar" blog, make sure to keep this source http://7832308.blog.51cto.com/7822308/1430460