拖动球

          在这里我想说的是在规定的区域用手拖动一个自定义的小球,很简单,首先定义一个画小球的类,在里面重写ondraw方法,然后在main文件中实例化刚才的类,之后呢给他一个触摸事件就会随你的手指移动了……

         1.先看我们画小球的那个类吧!代码如下:

              public class DrawView extends View

              {

                  public float currentX=40;

                  public float currentY=50;

                  public DrawView (Context context){

                                 super(context);

                       }            

                   protected void onDraw(Canvas canvas){

                           super.onDraw(canvas);

                           Paint p=new Paint();

                           p.setColor(Color.BULE);

                           canvas.drawCircle(currentX,currentY,15,p);

                      }

               }

          2.定义好圆后我们来写main里面的,还是看代码吧!

               public class MainActivity extends Activity{

                  protected void onCreate(){

                  super.onCreate(savedInstanceState);

                  LinearLayout root=(LinearLayout)findViewById(R.id.LinearLayout1);

                  final DrawView draw=new DrawView(this);

                  draw.setMinimumHeight(400);

                  draw.setMinimumWidth(500);

                  draw.setOnTouchListener(new OnTouchListener(){

                               public boolean onTouch(View arg0,MotionEvent arg1){

                              draw.currentX.=arg1.getX();

                               draw.currentY=arg1.getY();

                               //通知draw组件重新绘制

                                draw.invalidate();

                                retrun true;

                               }

                           });

                          root.addView(draw); 

                       }

                 }

  

posted @ 2013-08-04 16:07  萨拉克魔  阅读(187)  评论(0编辑  收藏  举报