如何在android上正确拖动视图 [英] how to use correct dragging of a view on android

查看:36
本文介绍了如何在android上正确拖动视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

android 上如何使用拖拽视图的解决方案似乎有很多.

it seems that there are a lot of solutions of how to use dragging of views on android .

然而,它们要么太慢,要么有问题.

however, they are either too slow or buggy.

一个已知的解决方案是使用 framelayout ,并且视图在使用 OnTouchListener 移动时简单地更改其 layoutParams ,如下所述:http://www.anddev.org/novice-tutorials-f8/android-drag-and-drop-of-normal-views-not-bitmaps-t13404.html但是,如果视图是 imageView ,当到达 framelayout 的最右侧(或最底部)时,图像会缩小.

a known solution is to have a framelayout , and the view simply changes its layoutParams as it moves using the OnTouchListener ,as described here: http://www.anddev.org/novice-tutorials-f8/android-drag-and-drop-of-normal-views-not-bitmaps-t13404.html however, if the view is an imageView , when reaching the most right (or most bottom) side of the framelayout , the image shrinks .

另一种可能的解决方案是使用画布来显示拖动的内容,如下所述:http://www.anddev.org/basic_drag_and_drop-t3095.html但是,我不确定如何将它用于复杂的视图.

another possible solution is to use the canvas in order to show the dragged content , as described here: http://www.anddev.org/basic_drag_and_drop-t3095.html however, i'm not sure how to use it for complex views.

有谁知道一个好的解决方案,让拖动视图的大小保持不变,无论它在容器中的哪个位置?

does anyone know of a good solution , one that let the size of the dragged view stay the same , no matter where it is in its container?

请帮帮我.

推荐答案

这里有一个简单的imageView拖拽的完整解决方案:

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;
      }
  });

这篇关于如何在android上正确拖动视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆