最近看到一个画图工具有个挺不错的拖动效果,感觉挺好,想想JS中实现拖拽功能用起来也挺爽,下面简单的做了一个拖拽效果的方法,们举例给按钮做一个拖拽的效果。
?
拖拽功能事件:
private OnTouchListener touch = new OnTouchListener() { int[] temp = new int[] { 0, 0 }; public boolean onTouch(View v, MotionEvent event) { int eventaction = event.getAction(); Log.i("&&&", "onTouchEvent:" + eventaction); int x = (int) event.getRawX(); int y = (int) event.getRawY(); switch (eventaction) { case MotionEvent.ACTION_DOWN: // temp[0] = (int) event.getX(); temp[1] = y - v.getTop(); break; case MotionEvent.ACTION_MOVE: // touch drag with the ball v.layout(x - temp[0], y - temp[1], x + v.getWidth() - temp[0], y - temp[1] + v.getHeight()); v.postInvalidate(); break; case MotionEvent.ACTION_UP: break; } return false; } };?
?
注册事件
button.setOnTouchListener(touch);?
?
当触摸按钮拖动时,即可看到按钮根据动作的方向移动,至于其他的控制,比如不能拖出边缘等等效果,自己给layout中设置即可。
?
?
?
1 楼 刀枪剑戟 2011-09-21
恩,不错。应该加上这个方法的解说的:
public void layout (int l, int t, int r, int b) Since: API Level 1 Assign a size and position to a view and all of its descendants This is the second phase of the layout mechanism. (The first is measuring). In this phase, each parent calls layout on all of its children to position them. This is typically done using the child measurements that were stored in the measure pass().Derived classes should not override this method. Derived classes with children should override onLayout. In that method, they should call layout on each of their children.Parametersl Left position, relative to parent t Top position, relative to parent r Right position, relative to parent b Bottom position, relative to parent