思想:想要实现拖动至任意位置,主要的是重写手指触摸事件,考虑的逻辑想法是触摸的位置和View的位置关系。
代码如下:
1.onTouchEvent
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
final int X = (int) event.getRawX();
final int Y = (int) event.getRawY();
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) getLayoutParams();
_xDelta = X - lParams.leftMargin;
_yDelta = Y - lParams.topMargin;
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_POINTER_DOWN:
break;
case MotionEvent.ACTION_POINTER_UP:
break;
case MotionEvent.ACTION_MOVE:
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) getLayoutParams();
layoutParams.leftMargin = X - _xDelta;
layoutParams.topMargin = Y - _yDelta;
MoveImageView.this.setLayoutParams(layoutParams); //自己继承VIEW的this
break;
}
invalidate();
return true;
}
2.Layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.aierjun.moveview.view.MoveImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@mipmap/ic_launcher"/>
</RelativeLayout>
注意:次方法Layout中的长宽必须给定,不然效果会改变。
android:layout_width="100dp"
android:layout_height="100dp"
源码下载地址:http://download.csdn.net/detail/aierjun/9717601
git地址:http://git.oschina.net/aierjun/MoveView