随着学习,经验是增加了,但是还是很缺少经验,我分享这个代码只是更大家分享小小的成果,顺便永久性保存这个代码,以后用到的时候可以拿来就用,需要改正也是很方便的,毕竟自己动脑子写的,每一步的功能都理解的很清楚。
package com.example.ontouchmove;
import android.os.Bundle;
import android.app.Activity;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.MotionEvent;
import android.widget.AbsoluteLayout;
import android.widget.ImageView;
public class MainActivity extends Activity {
private ImageView imgv;
private float m;
private float d;
private float x;
private float y;
private int imgWidth;
private int imgHeight;
private float mY;
private float mX;
private int ScreenX;
private int ScreenY;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgv=(ImageView) findViewById(R.id.imageView1);
/* 取得屏幕对象 */
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
/* 取得屏幕解析像素 */
ScreenX = dm.widthPixels;
ScreenY = dm.heightPixels;
/* 设定图片的宽高 */
imgWidth = 100;
imgHeight =100;
}
@SuppressWarnings("deprecation")
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
/*获取手触屏的位置*/
m=event.getX();
d=event.getY();
x = event.getX()-45;
y = event.getY()-160;
/*默认微调图片与指针的相对位置*/
mX=x-(imgWidth/2);
mY=y-(imgHeight/2);
/*分开处理触摸的时间*/
switch (event.getAction()) {
/*点屏幕*/
case MotionEvent.ACTION_DOWN :
imgv.setLayoutParams(new
AbsoluteLayout.LayoutParams
(imgWidth, imgHeight, (int)mX,(int)mY));
break;
/*移动位置*/
case MotionEvent.ACTION_MOVE :
imgv.setLayoutParams(new
AbsoluteLayout.LayoutParams
(imgWidth, imgHeight, (int)mX,(int)mY));
break;
/*离开屏幕*/
case MotionEvent.ACTION_UP :
imgv.setLayoutParams(new
AbsoluteLayout.LayoutParams
(imgWidth, imgHeight, (int)mX,(int)mY));
break;
default:
break;
}
return true;
}
}
热门评论
是指图片随着手指动么?建议看看 ViewDragHelper 接口。