First, customize a view subclass:
Package Com.example.androidtest0.myview;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 classDrawview extends View { Public floatCurrentX = +; Public floatCurrentY = -; //define, and create brushesPaint p =NewPaint (); PublicDrawview (Context context) {super (context); } PublicDrawview (Context context, AttributeSet Attrs) {Super (context, attrs); } @Overrideprotected voidOnDraw (canvas canvas) {super.ondraw (canvas); //set the color of a brushP.setcolor (color.red); //draw a small ballCanvas.drawcircle (CurrentX, CurrentY, the, p); } /** * Override event handling method for touch event of this component*/@Override PublicBoolean ontouchevent (motioneventEvent) { //Modify CurrentX, currenty two propertiesCurrentX =Event. GetX (); CurrentY=Event. GetY (); //notifies the current component to redraw itselfinvalidate (); return true; }}
Main interface xml:
Custom_layout.xml
<pre name="Code" class="Java"><?xml version="1.0"encoding="Utf-8"? ><linearlayout xmlns:android="http://schemas.android.com/apk/res/android"Android:layout_width="match_parent"Android:layout_height="match_parent"Android:id="@+id/root"android:orientation="Vertical"></LinearLayout>
The main activity file is as follows:
Package Com.example.androidtest0;import Com.example.androidtest0.myview.drawview;import android.app.Activity; Import Android.os.bundle;import android.widget.LinearLayout; Public class CustomView extends Activity { @Override protectedvoid onCreate (Bundle Savedinstancestate) { super.oncreate (savedinstancestate); Setcontentview (r.layout.custom_layout); }}
Effect:
Besides:
It can also be done in XML: It is also the first subclass of a view, as in the above. Then the main interface XML is as follows:
<?xml version="1.0"encoding="Utf-8"? ><linearlayout xmlns:android="http://schemas.android.com/apk/res/android"Android:layout_width="match_parent"Android:layout_height="match_parent"Android:id="@+id/root"android:orientation="Vertical"> <Com.example.androidtest0.myView.DrawView android:layout_width="match_parent"android:layout_height="match_parent"/></linearlayout>
The main activity file is as follows:
Package Com.example.androidtest0;import Com.example.androidtest0.myview.drawview;import android.app.Activity; Import Android.os.bundle;import android.widget.LinearLayout; Public class CustomView extends Activity { @Override protectedvoid onCreate (Bundle Savedinstancestate) { super.oncreate (savedinstancestate); Setcontentview (r.layout.custom_layout); }}
Android custom components automatically draw circles with your fingers