This example is a preliminary introduction to the custom view. We need to design a ball moving with the finger. The principle is to obtain the coordinates of the finger at any time, and then change the coordinates of the custom view in real time on the coordinates. This view only draws a circle.
Custom View
Drawview. Java
Package COM. kale. drawview; import android. annotation. suppresslint; import android. content. context; import android. graphics. canvas; import android. graphics. color; import android. graphics. paint; import android. util. attributeset; import android. view. motionevent; import android. view. view; public class drawview extends view {public float currentx = 60; public float currenty = 60; // define, create paint = new paint (); Public drawview (context) {super (context);} public drawview (context, attributeset set) {super (context, set) ;}@ override public void ondraw (canvas) {super. ondraw (canvas); // you can specify the paint color. setcolor (color. red); // draw a small circle canvas. drawcircle (currentx, currenty, 50, paint);} // Method for rewriting the touch time of the component 2 @ override public Boolean ontouchevent (motionevent event) {// modify the coordinates currentx = event. getx (); currenty = event. gety (); // notification component, redraw your own invalidate (); // return true indicating that the method has handled the event return true ;}}
Layout File
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/root_relativeLayout_id" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="${relativePackage}.${activityClass}" > <com.kale.drawview.DrawView android:layout_width="match_parent" android:layout_height="match_parent"/></RelativeLayout>
Of course, we can also put the custom control in layout directly in the code without layout files.
Package COM. kale. drawview; import android. app. activity; import android. OS. bundle; import android. view. menu; import android. view. menuitem; import android. widget. relativelayout; public class mainactivity extends activity {@ override protected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_main);/* relativelayout root = (relativelayout) findviewbyid (R. id. root_relativelayout_id); Final drawview = new drawview (this); // sets the maximum degree of parallelism of the component drawview. setminimumheight (300); drawview. setminimumwidth (500); root. addview (drawview );*/}}