The Android layout file is below layout and is usually named *.xml. By defining the view in XML as XML, however, it is often necessary to customize the view in an Android application, which requires a class that inherits from the Android View. Today wrote a small game, the mouse movement, the view inside the red ball with the mouse movement and move.
Userdefineviewactivity.java
package Com.example.androidexample;import Android.app.activity;import Android.os.bundle;import android.view.MotionEvent; Import Android.view.view;import Android.view.view.ontouchlistener;import Android.widget.linearlayout;public class Userdefineviewactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {//TODO Auto-generated method Stubsuper.oncreate (savedinstancestate); Setcontentview (R.layout.activity_draw); LinearLayout layout = (linearlayout) Findviewbyid (r.id.drawlayout); Final Drawview Drawview = new Drawview (this); Layout.setminimumheight (+); layout.setminimumwidth (300); Drawview.setontouchlistener (New Ontouchlistener () {@Overridepublic Boolean OnTouch (view view, Motionevent event) {// TODO auto-generated Method Stubdrawview.currentx = Event.getx ();d rawview.currenty = event.gety ();d rawview.invalidate ( ); return true;}); Layout.addview (Drawview);}}
The following are classes that inherit from Android View
Package Com.example.androidexample;import Android.content.context;import Android.graphics.canvas;import Android.graphics.color;import Android.graphics.paint;import Android.view.view;public class DrawView extends View { Public float currentx;public float currenty; @Overrideprotected void OnDraw (canvas canvas) {//TODO auto-generated method s Tubsuper.ondraw (canvas); Paint paint = new paint ();p aint.setcolor (color.red), Canvas.drawcircle (CurrentX, currenty, and paint);} Public Drawview (Context context) {super (context);//TODO auto-generated constructor stub}}
Interface Layout File Activity_draw.xml
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android " android:id=" @+id/drawlayout " android:layout_width=" match_parent " android:layout_height=" Match_parent " android:orientation=" vertical "> </LinearLayout>
Note: Do not forget to register userdefineviewactivity to Androidmanifest.xml
Run effect
Android Custom View