Generally, when drawing a graphical interface, we use the view in the configuration file. Can we define the view we need? The answer is yes, of course. We can use a paint brush to draw the view we need on the canvas and reference it on the interface. However, for operations such as drawing, we do not recommend that you use it in the main UI thread. we can implement it by inheriting from SurfaceView or from View. Let's take a look at it.
I. inherit the custom View to complete the custom View
A custom view is undoubtedly the process of drawing the view style you want and referencing it to the project. Let's take a look at how to customize a view?
1: Customize the class inherited from the View to complete the painting.
1) Add a constructor, instantiate the paint brush in the constructor, and set the color of the paint brush.
2) override the onDraw method: the parameter is canvas. You can set the background color of the canvas to complete drawing.
// Custom View inherited from Viewpublic class MyView extends View {private Paint paint; // declare the paint brush public MyView (Context context) {super (context); Paint = new Paint (); // instantiate the paint brush paint. setColor (Color. GREEN); // set the paint brush color} @ Override protected void onDraw (Canvas canvas) {super. onDraw (canvas); canvas. drawColor (Color. WHITE); // set the background color of the canvas // draw a rectangle, x coordinate of the starting point of the parameter, y coordinate of the starting point, width, height, and paint brush object) canvas. drawRect (10, 10,100,100, paint );}} |
2: Introduce custom view objects in the onCreate method on the main interface
setContentView(new MyView(this)); |
3: The Custom view style is displayed on the main interface, as shown in the following figure.
650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/0951423210-0.jpg "title =" Unnamed .bmp "/>
II. The application inherits from the View to implement a "certain motion" of the rectangle block.
1. Add a constructor to initialize the paint brush and set attributes.
public MyRect(Context context) { super(context); paint.setColor(Color.GREEN); } |
2: inherit from the onDraw method in the View class to draw rectangles.
Private float x = 0; // start x, y coordinate private float y = 0; private float speedx = 50; // width and height of the rectangle private float speedy = 50; private float addy = 2; // The increment value of x and y is private float addx = 2 each time it is moved; // you can specify the canvas background color. drawColor (Color. WHITE); // draw a canvas with a rectangle. drawRect (x, y, x + speedx, y + speedy, paint); y + = addy; // if (y <0) {// if the upper boundary of y is out of the positive value range, it runs to the top of the mobile phone screen. addy = Math. abs (addy); // set the increment value to + and run down.} if (y> getHeight ()-speedy) {// If the bottom boundary of y exceeds the screen range addy =-Math. abs (addy); // set the increment value to negative and run up} x + = addx; // The x coordinate is worth changing if (x <0) {// If the left boundary of x is out of the positive value range, it goes to the left side of the mobile phone screen addx = Math. abs (addx);} if (x> getWidth ()-speedx) {// if the right boundary of x exceeds the screen range addx =-Math. abs (addx); // sets the increment value to negative and runs to the left} |
3: Create a Handler object to implement the Handler object. In the handleMessage method, the handleMessage method is used to implement the re-painting.
Private Handler handler = new Handler () {public void handleMessage (android. OS. Message msg) {invalidate (); // redraw };}; |
4: add the start and end methods of the timer, and add the handler method to send messages in the Start timer.
// Start public void startTimer () {timer = new Timer (); task = new TimerTask () {@ Override public void run () {// send the message handler. sendEmptyMessage (0) ;}}; // start the timer. schedule (task, 100, 10);} // terminate the timer public void stopTimer () {timer. cancel ();} |
5: In the main interface, add an OnTouchListener listener to the custom view to achieve a "certain motion" Effect Based on the triggered action.
Public class MainActivity extends Activity implements OnTouchListener {private MyRect myRect; // declare the custom view private int flag = 0; // flag @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); myRect = new MyRect (this); // instantiate the custom view setContentView (myRect); // Add the view myRect. setOnTouchListener (this); // load listener} @ Override public boolean onTouch (View v, MotionEvent event) {switch (event. getAction () {case MotionEvent. ACTION_DOWN: // do you want to press the operation if (flag = 0) {// if it is the first time you click myRect. startTimer (); // start, let him go flag = 1; // change flag} else if (flag = 1) {// if you click myRect again. stopTimer (); // It is stopped, so that the flag cannot be changed to 0; // modify the flag} break;} return true; // note that it will be triggered only when true }} |
6: Result: This method is used to achieve the "certain motion" effect of the rectangle. You can try it on your own.
3. inherit the custom view implemented by SurfaceView
The normal operation of drawing static images is fine, but we do not recommend that you directly place them in the main UI thread when drawing dynamic or time-consuming operations, we inherit from SurfaceView and create a thread on our own. It is better to complete the operation in this thread.
Application: we use this method to freely move the rectangle.
1: Inherit from SurfaceView, implement the SurfaceHolder. Callback interface, and override the three methods.
public class MySurface extends SurfaceView implements SurfaceHolder.Callback |
1) surfaceCreated method: This method is triggered when SurfaceView is created for the first time. It mainly completes initialization. do not complete the painting operation here.
2) surfaceChanged method: This method is triggered when the Surface state changes.
3) surfaceDestoryed method: the State triggered before Surface destruction, used to clear resources.
2: Add a constructor to initialize the paint brush and set its attributes, and add a callback.
Public MySurface (Context context) {super (context); paint. setColor (Color. GREEN); // set the color of the paint brush to getHolder (). addCallback (this); // Add callback} |
3. Customize the drawing method to draw a rectangle.
Private float x = 0; // start x, y coordinate private float y = 0; private float speedx = 50; // width and height of the rectangle private float speedy = 50; private float addy = 2; // The increment value of x and y for each move is private float addx = 2; public void draw () {// lock the canvas and perform all drawing operations, the operation must be completed between locks. Otherwise, the Canvas canvas = getHolder () error occurs (). lockCanvas (); // set the canvas background color canvas. drawColor (Color. WHITE); // draw a canvas with a rectangle. drawRect (x, y, x + speedx, y + speedy, paint); y + = addy; // if (y <0) {// if the upper boundary of y is out of the positive value range, it runs to the top of the mobile phone screen. addy = Math. abs (addy); // set the increment value to + and run down.} if (y> getHeight ()-speedy) {// If the bottom boundary of y exceeds the screen range addy =-Math. abs (addy); // set the increment value to negative and run up} x + = addx; // The x coordinate is worth changing if (x <0) {// If the left boundary of x is out of the positive value range, it goes to the left side of the mobile phone screen addx = Math. abs (addx);} if (x> getWidth ()-speedx) {// if the right boundary of x exceeds the screen range addx =-Math. abs (addx); // sets the increment value to negative and runs to the left.} // unlock the canvas getHolder (). unlockCanvasAndPost (canvas );} |
4: Customize the timer startup and pause, and call the drawing method in the timer
// Start public void startTImer () {timer = new Timer (); // instantiate the timer task = new TimerTask () {@ Override public void run () {draw (); // call the drawing method}; // start the timer. schedule (task,);} // stop the timer public void stopTimer () {timer. cancel ();} |
5: add the reference of the Start timer and disable the timer method to the three methods that are rewritten in the interface to pay attention to the reference position)
// Call the method for starting the timer @ Override public void surfaceChanged (SurfaceHolder holder, int format, int width, int height) {startTImer () ;}@ Override public void surfaceCreated (SurfaceHolder holder) {}// call the method for terminating the timer @ Override public void surfaceDestroyed (SurfaceHolder holder) {stopTimer ();} |
6. Result: The Green rectangular block is moved freely within the screen range.
Custom views are very useful. We have to remember them well... 650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/0951421934-1.gif "/>
This article is from the "Schindler" blog, please be sure to keep this source http://cinderella7.blog.51cto.com/7607653/1296185