android drag view smooth

限于喜欢 提交于 2019-12-04 16:28:24

问题


I have to drag some views on screen. I am modifying their position by changing left and top of their layout parameters from motion event on ACTION_MOVE from touch listener. Is there a way to "drag" items more smooth? Because tis kind of "dragging" is no smooth at all... Here is the code

public boolean onTouch(View view, MotionEvent motionEvent) {
    switch (motionEvent.getAction()) {
        case MotionEvent.ACTION_DOWN:
            dx = (int) motionEvent.getX();
            dy = (int) motionEvent.getY();
            break;

        case MotionEvent.ACTION_MOVE:
            int x = (int) motionEvent.getX();
            int y = (int) motionEvent.getY();
            RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) view.getLayoutParams();
            int left = lp.leftMargin + (x - dx);
            int top = lp.topMargin + (y - dy);
            lp.leftMargin = left;
            lp.topMargin = top;
            view.setLayoutParams(lp);
            break;
    }
    return true;
}

回答1:


Try to use motionEvent.getRawX() and motionEvent.getRawY() instead of getY and getX




回答2:


You need not to use LayoutParameters to drag. You can do it by just setting the X and Y coordinates of the view. You can read more on this here.

You can do something like this.

  @Override
  public boolean onTouch(View view, MotionEvent event) {
    switch (event.getActionMasked()) {
      case MotionEvent.ACTION_DOWN:
        dX = view.getX() - event.getRawX();
        dY = view.getY() - event.getRawY();
        break;

      case MotionEvent.ACTION_MOVE:
        view.setY(event.getRawY() + dY);
        view.setX(event.getRawX() + dX);
        break;

      default:
        return false;
    }
    return true;
  }



回答3:


The reason of non-smooth move is integer value of leftMargin and topMargin.
For smooth move position should be float.
This could help.




回答4:


It would be useful to see how you are processing your ACTION_MOVE events. Are you utilizing all the points using event.getHistorical() method? If that does not give you a smoother drag, other idea might be to interpolate points on the path. I believe there will be a trade-off between achieving smoothness of movement and quick response to user's touch. HTH.




回答5:


You should round your ints, also using margins is not going to be very smooth, use a different layout and set X and Y coordinates according to screen dimensions.



来源:https://stackoverflow.com/questions/8535599/android-drag-view-smooth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!