Android custom components automatically circle with fingers
First, define 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 class DrawView extends View {public float currentX = 40; public float currentY = 50; // define and create Paint p = new Paint (); public DrawView (Context context) {super (context);} public DrawView (Context context, AttributeSet attrs) {super (context, attrs);} @ Overrideprotected void onDraw (Canvas canvas Canvas) {super. onDraw (canvas); // sets the paint brush color p. setColor (Color. RED); // draw a small ball canvas. drawCircle (currentX, currentY, 15, p);}/*** rewrite event processing method for touch events of the component */@ Overridepublic boolean onTouchEvent (MotionEvent event) {// modify the currentX and currentY attributes currentX = event. getX (); currentY = event. getY (); // notify the current component to redraw its own invalidate (); return true ;}}
Main Interface XML:
Custom_layout.xml
Main activity:
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 {@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. custom_layout); // obtain the LinearLayout container LinearLayout root = (LinearLayout) findViewById (R. id. root); // create the DrawView component final DrawView drawView = new DrawView (this); // set the minimum width and height of the custom component drawView. setMinimumWidth (10); drawView. setMinimumHeight (10); root. addView (drawView );}}
Effect:
<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink">
VcD4KPHA + s/20y9auzekjuw.vcd4kpha + u7m/ydLU08NYTUy1xLe9yr2jutKyysfK18/fingerprint + PHByZSBjbGFzcz0 = "brush: java;">
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 {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.custom_layout);}}