how to use correct dragging of a view on android

丶灬走出姿态 提交于 2019-11-28 08:49:41

Here's a complete solution for a simple imageView dragging:

findViewById(R.id.imageView).setOnTouchListener(new OnTouchListener()
  {
    int prevX,prevY;

    @Override
    public boolean onTouch(final View v,final MotionEvent event)
      {
      final FrameLayout.LayoutParams par=(FrameLayout.LayoutParams)v.getLayoutParams();
      switch(event.getAction())
        {
        case MotionEvent.ACTION_MOVE:
          {
          par.topMargin+=(int)event.getRawY()-prevY;
          prevY=(int)event.getRawY();
          par.leftMargin+=(int)event.getRawX()-prevX;
          prevX=(int)event.getRawX();
          v.setLayoutParams(par);
          return true;
          }
        case MotionEvent.ACTION_UP:
          {
          par.topMargin+=(int)event.getRawY()-prevY;
          par.leftMargin+=(int)event.getRawX()-prevX;
          v.setLayoutParams(par);
          return true;
          }
        case MotionEvent.ACTION_DOWN:
          {
          prevX=(int)event.getRawX();
          prevY=(int)event.getRawY();
          par.bottomMargin=-2*v.getHeight();
          par.rightMargin=-2*v.getWidth();
          v.setLayoutParams(par);
          return true;
          }
        }
      return false;
      }
  });

I am using drag and drop in a current project, where the various Views are placed within a RelativeLayout according to LayoutParams applied to them. Like you, I found that Views would 'shrink' when reaching the right or bottom of the ViewGroup container. It's probably quite obvious that this will happen, really, considering that during the measure and layout phases, the system is going to determine that a given View is suddenly going to have to have much smaller dimensions than you actually wish if it's still going to be able to fit into the parent when placed near the extremes.

A very simple solution I've done to get around that at the moment is to simply oversize my ViewGroup relative to the screen size.

Furthermore, you may decide that you don't actually want Views to appear partially off-screen, in which case you'd use some program logic to prevent the View objects' margins being set such that the Views are allowed to go off the parent container's boundary.

Another solution might be to override onMeasure() or similar to force the child View to force a larger size than the parent deems is available to it -- if that's possible -- to force the View to be placed there in the desired size, overlapping the edge. That's just an idea off the top of my head though and have not investigated it.

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