Next, I will share with you the usage of surfaceview in the game. This is my first blog post on csdn. I hope you can correct the errors and errors. Thank you.
See the code below:
Mysurfaceview. Java is the class for customizing surfaceview
Package com. guu. view;
Import Android. content. context;
Import Android. Graphics. Canvas;
Import Android. Graphics. color;
Import Android. Graphics. paint;
Import Android. View. surfaceholder;
Import Android. View. surfaceview;
Public class mysurfaceview extends surfaceview implements runnable, surfaceholder. Callback {
// X coordinate of the center of the ball
Private int x = 100;
// Ball radius
Private int r = 15;
// Y coordinate of the center of the ball
Private int y = R;
// Screen height
Private int screenheight;
// Used to control surfaceview
Private surfaceholder holder;
// Define a paint brush
Private paint;
// Define a canvas
Private canvas;
// Check whether the thread is alive
Private Boolean islive;
Public mysurfaceview (context ){
Super (context );
Holder = This. getholder ();
// Add listeners for holder
Holder. addcallback (this );
Paint = new paint ();
// Set the focus
Setfocusable (true );
}
/**
* Drawing Method
*/
Public void mydraw (){
// Edit the image
Canvas = holder. lockcanvas ();
If (canvas! = NULL ){
Try {
// Screen Flushing
Canvas. drawcolor (color. Black );
// Set the paint brush color to green
Paint. setcolor (color. Green );
// Circle
Canvas. drawcircle (X, Y, R, paint );
} Catch (exception e ){
E. printstacktrace ();
} Finally {
// Complete image editing
Holder. unlockcanvasandpost (canvas );
}
}
}
Public void changelocation (){
// Return the start position when the ball reaches the bottom of the screen
If (Y + r> = screenheight ){
Y = R;
} Else {
Y + = 3;
}
}
@ Override
Public void run (){
While (islive ){
// Call the Drawing Method
Mydraw ();
Try {
Thread. Sleep (50 );
} Catch (interruptedexception e ){
E. printstacktrace ();
}
// Change the coordinates of the center
Changelocation ();
}
}
@ Override
Public void surfacechanged (surfaceholder arg0, int arg1, int arg2, int arg3 ){
}
// This method is called when the screen is created for the first time
@ Override
Public void surfacecreated (surfaceholder arg0 ){
System. Out. println ("surfacecreated ");
Screenheight = This. getheight ();
Islive = true;
New thread (this). Start ();
}
// Called when the screen is destroyed
@ Override
Public void surfacedestroyed (surfaceholder arg0 ){
Islive = false;
System. Out. println ("surfacedestroyed ");
}
}
The code for the main activity is as follows:
Package com. guu. view;
Import Android. App. activity;
Import Android. OS. Bundle;
Public class mainactivity extends activity {
/** Called when the activity is first created .*/
@ Override
Public void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (New mysurfaceview (this ));
}
}
After running, the result is a process of falling green balls.