Android应用小实例--跟随手指的小球
fmms
13年前
实现效果图:
实现方式:
继承View类自己重绘一个圆,然后将这个自定义的继承于View类的加入到当前的Activity并且为这个自定义的View控件添加一个onTouchLitener事件
自定义组件继承于View类:
package com.jiahui.draw; 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=40; public float currentY=50; //必须重写一个构造方法 public DrawView(Context context) { super(context); // TODO Auto-generated constructor stub } //重写onDraw方法通过Canvas绘画 @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //创建画笔 Paint paint=new Paint(); paint.setColor(Color.RED); //绘制一个小圆 canvas.drawCircle(currentX, currentY, 25, paint); } }将自定义的组件添加到当前的Activity
package com.jiahui.draw; import android.app.Activity; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.widget.LinearLayout; public class CustomeViewActivity extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); LinearLayout root=(LinearLayout) findViewById(R.id.root); //创建一个自己继承于View的对象 final DrawView drawView=new DrawView(this); //设置自定义组件的最大宽度和高度 drawView.setMinimumWidth(300); drawView.setMinimumHeight(500); drawView.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { drawView.currentX=event.getX(); drawView.currentY=event.getY(); //重绘 drawView.invalidate(); //返回true表明算是方法已经处理该事件 return true; } }); root.addView(drawView); } }main.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:background="#99FFCC" android:id="@+id/root"> </LinearLayout>如转载请声明文章出处:http://blog.csdn.net/jiahui524