1. Defining Mypaintview Components
public class mypaintview extends view { private list< Point> allpoint = new arraylist<point> (); public Mypaintview (context context, attributeset attrs) { super (context, attrs); Super.setbackgroundcolor (color.white); super.setontouchlistener (New ontouchlistenerimp ()); } private class ontouchlistenerimp implements ontouchlistener { @Override public boolean ontouch (View v, Motionevent event) { // The point class records the current x and Y coordinates &nbSp; point p = new point (int) event.getx (), (int) Event.getY ()); if (Event.getaction () == Motionevent.action_down) { //judgment lift allPoint = new ArrayList<Point> ( //); Start a new record Allpoint.add (p); //Record coordinate points } else if (Event.getaction () == motionevent.action_up) { allpoint.add (p); // Record coordinate points MyPaintView.this.postInvalidate (); //Redraw } return true; } } @Override protected void ondraw (Canvas canvas) { //for drawing paint p = new paint (); p.setcolor (color.red); //Set Color if ( Allpoint.size () >1) { iterator <point> iter = allpoint.iterator (); Point first = null; point last = null; while (Iter.hasNext ()) { //iterative output if (first == null) { first = (point) iter.next (); } else { if (last != null) { first = last; //Modify Start point } last = (point) iter.next (); // End Point canvas.drawline (first.x,first.y,last.x,last.y,p); } } } super.ondraw (canvas); }}
2. In Activity_main.xml, be aware that Mypaintview is customized to include the full package name
<com.example.administrator.ontouchtest.mypaintview android:layout_width= "Fill_parent" android:layout_height= " Fill_parent "android:id=" @+id/paintview "/>
3. Writing mainactivity
public class Mainactivity extends Appcompatactivity {private TextView info = null; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); }}
Android Phone Touch Draw line