============问题描述============
android怎么实现 图像随着手指的移动而移动 当点击一个地方的时候图片能够移动到那个地方 希望给出具体的示例代码
============解决方案1============
activity内容:
public class CustomView extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } }
DrawView组件:
public class DrawView extends View { public float currentX = 40; public float currentY = 50; /** * @param context */ public DrawView(Context context , AttributeSet set) { super(context , set); } @Override public void onDraw (Canvas canvas) { super.onDraw(canvas); //创建画笔 Paint p = new Paint(); //设置画笔的颜色 p.setColor(Color.RED); //绘制一个小圆(作为小球) canvas.drawCircle(currentX , currentY , 15 , p); } @Override public boolean onTouchEvent(MotionEvent event) { //当前组件的currentX、currentY两个属性 this.currentX = event.getX(); this.currentY = event.getY(); //通知改组件重绘 this.invalidate(); //返回true表明处理方法已经处理该事件 return true; } }
xml布局文件:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <!-- 使用自定义组件 --> <org.crazyit.event.DrawView android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout>
代码引用自《疯狂安卓讲义》李刚
时间: 2024-10-04 23:12:59