当前位置: 代码迷 >> Android >> Android开发——追随手指的小球实现
  详细解决方案

Android开发——追随手指的小球实现

热度:63   发布时间:2016-05-01 12:30:16.0
Android开发——跟随手指的小球实现

今天要实现的是一个跟随手指的小球,说白了就是让小球按着手指滑动的轨迹运动,实现起来还是比较容易的。

用到的类是drawView,我们先自定义一个DrawView组件。

DrawView.java:

?

package cn.csdn.android.view;

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 = 300;
public float currentY = 500;

public DrawView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}

@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
Paint p = new Paint();
p.setColor(Color.RED);
canvas.drawCircle(currentX, currentY, 15, p);
}


}

==================================

在main.xml文件中给一个android:id="@+id/root";

然后写java代码实现跟踪效果:

CustomView.java

package cn.csdn.android.view;

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 CustomViewActivity extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

LinearLayout main = (LinearLayout) findViewById(R.id.root);
final DrawView draw = new DrawView(this);
draw.setMinimumWidth(300);
draw.setMinimumHeight(500);

draw.setOnTouchListener(new OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {
draw.currentX = event.getX();
draw.currentY = event.getY();
draw.invalidate();
return true;
}
});
main.addView(draw);
}

}

?

  相关解决方案