Android开发——跟随手指的小球实现
今天要實現(xiàn)的是一個跟隨手指的小球,說白了就是讓小球按著手指滑動的軌跡運動,實現(xiàn)起來還是比較容易的。
用到的類是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代碼實現(xiàn)跟蹤效果:
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);
?}
?
}
總結(jié)
以上是生活随笔為你收集整理的Android开发——跟随手指的小球实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Ubuntu 相关命令行工具
- 下一篇: 完美的单例模式创建