当前位置: 移动技术网 > IT编程>移动开发>Android > Android 自定义可拖拽View界面渲染刷新后不会自动回到起始位置

Android 自定义可拖拽View界面渲染刷新后不会自动回到起始位置

2019年07月24日  | 移动技术网IT编程  | 我要评论

马桶有哪些品牌,油价调整,爱得利亚

以自定义imageview为例:

/**
 * 可拖拽imageview
 * created by admin on 2017/2/21.
 */
public class floatingimageview extends imageview{
  public floatingimageview(context context) {
    super(context);
  }
  public floatingimageview(context context, attributeset attrs) {
    super(context, attrs);
  }
  public floatingimageview(context context, attributeset attrs, int defstyleattr) {
    super(context, attrs, defstyleattr);
  }
  @targetapi(build.version_codes.lollipop)
  public floatingimageview(context context, attributeset attrs, int defstyleattr, int defstyleres) {
    super(context, attrs, defstyleattr, defstyleres);
  }
  int startx;
  int starty;
  int left;
  int top;
  int[] temp = new int[]{ 0, 0 };
  @override
  public boolean ontouchevent(motionevent event) {
    boolean ismove = false;
    int x = (int) event.getrawx();
    int y = (int) event.getrawy();
    switch (event.getaction()){
      case motionevent.action_down: // touch down so check if the
        startx = x;
        starty = y;
        temp[0] = (int) event.getx();
        temp[1] = y - gettop();
        break;
      case motionevent.action_move: // touch drag with the ball
        left = x - temp[0];
        top = y - temp[1];
        if(left < 0){//控制左边界不超出
          left = 0;
        }
        layout(left, top, left + getwidth(),top + getheight());//自由拖拽
        break;
      case motionevent.action_up:
        if (math.abs(x - startx) > 2 || math.abs(y - starty) > 2){//判断是否移动,再一定范围内不算是移动,解决触发事件冲突
          //将最后拖拽的位置定下来,否则页面刷新渲染后按钮会自动回到初始位置
          //注意父容器
          relativelayout.layoutparams lp = (relativelayout.layoutparams) getlayoutparams();
          lp.setmargins(left, top,0,0);
          setlayoutparams(lp);
          //确定是拖拽
          ismove = true;
         }
        break;
    }
    return ismove ? true : super.ontouchevent(event);
   }
}

以上所述是小编给大家介绍的android 自定义可拖拽view界面渲染刷新后不会自动回到起始位置,希望对大家有所帮助

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网