Android custom circular view to achieve the effect that the ball moves with the finger

This example shares the specific code of Android to realize the effect of small ball following finger movement for your reference. The specific contents are as follows

1、 Demand function

The finger slides on the screen, and the red ball always follows the finger.

Implementation ideas:

1) Customize the view and draw a circle as a small ball in OnDraw;

2) Rewrite the ontouchevent method of the custom view, record the touch screen coordinates, and redraw the ball with the new coordinates;

3) Reference the custom view layout in the layout and run the program to realize the effect of following the finger movement.

Key technical points

Custom view application, touch event processing, canvas drawing, paint application.

Implementation steps

1. Create a new project named ballviewdemo and activity named ballactivity;

2. Create a custom view class ballview. Custom attribute: ball_ size;

Create a new attrs.xml file and customize the attribute ball_ Size, you can set the size of the small ball in the layout file

3. Inherit view to implement custom view;

1) Rewrite three construction methods of custom view

2) Initialize custom properties

3) Handle the resource recycling logic for the user-defined attribute object

4. Implement ondraw() method;

1) Set the screen to white with canvas

2) Set the brush color to red

3) Draw a small circle as a small ball, and the radius is set through custom attributes

5. Implement the ontouchevent method to handle touch events;

1) Implement motionevent.action_ Down, record the pressed x, y coordinates

2) Implement motionevent.action_ Move records the X, y coordinates of the movement

3) Implement motionevent.action_ Up records the raised x, y coordinates

4) Use the postinvalidate () method to redraw the ball and follow the finger

2、 Renderings

3、 Function code

The first way to achieve the effect: customize the view class ballview to cooperate with the XML file

XML file

The second way to achieve the effect: reference the custom view class ballview in the function code

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>