我们为view添加onTouch事件,获取移动过程中,手指相对屏幕的位置信息:[code]
@Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: break; case MotionEvent.ACTION_MOVE: moveViewWithFinger(view, event.getRawX(), event.getRawY()); break; case MotionEvent.ACTION_UP: break; } return true; }
/** * 设置View的布局属性,使得view随着手指移动 注意:view所在的布局必须使用RelativeLayout 而且不得设置居中等样式 * * @param view * @param rawX * @param rawY */ private void moveViewWithFinger(View view, float rawX, float rawY) { RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) view .getLayoutParams(); params.leftMargin = (int) rawX - ivMove.getWidth() / 2; params.topMargin = (int) rawY - topTitleHeight - ivMove.getHeight() / 2; view.setLayoutParams(params); }
/** * 通过layout方法,移动view * 优点:对view所在的布局,要求不苛刻,不要是RelativeLayout,而且可以修改view的大小 * * @param view * @param rawX * @param rawY */ private void moveViewByLayout(View view, int rawX, int rawY) { int left = rawX - ivMove.getWidth() / 2; int top = rawY - topTitleHeight - ivMove.getHeight() / 2; int width = left + view.getWidth(); int height = top + view.getHeight(); view.layout(left, top, width, height); }
-------------------------------------------------------------------
更多交流,Android开发联盟QQ群:272209595