当前位置: 移动技术网 > IT编程>移动开发>Android > Android实现按钮拖拽还原功能

Android实现按钮拖拽还原功能

2020年03月09日  | 移动技术网IT编程  | 我要评论

中国古钱币价格,天津站,潮汐王子

具体代码如下所示:

public class mainactivity extends appcompatactivity {
  private imagebutton ibok ;
  private int lastx;
  private int lasty;
  private int startleft;
  private int startright;
  private int starttop;
  private int startbottom;
  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_main);
    ibok = (imagebutton) findviewbyid(r.id.ib_ok);
    ibok.setontouchlistener(new view.ontouchlistener() {
      @override
      public boolean ontouch(view v, motionevent event) {
        int action = event.getaction();
        //获取手机触摸的坐标
        int x = (int) event.getx();
        int y = (int) event.gety();
        switch (action) {
          case motionevent.action_down://按下,获取小球初始的位置
            startleft = ibok.getleft();
            startright = ibok.getright();
            starttop = ibok.gettop();
            startbottom = ibok.getbottom();
            lastx = x;
            lasty = y;
            break;
          case motionevent.action_move://移动,小球跟随手指的移动
            int offsetx = x - lastx;
            int offsety = y - lasty;
            ibok.layout(ibok.getleft() + offsetx, ibok.gettop() + offsety,
                ibok.getright() + offsetx, ibok.getbottom() + offsety);
            break;
          case motionevent.action_up://当手指抬起时,回到小球初始的位置
            ibok.layout(startleft, starttop, startright, startbottom);
            break;
        }
        return true;

      }
    });
  }
  
}

代码解释: 图一,是完整代码。按钮可以随意拖拽(x+y轴),抬手,按钮恢复到初始位置。 图二区域,按此方式可以实现横向拖拽,类似接打电话动画效果,左边接听,右边挂断。

总结

以上所述是小编给大家介绍的android实现按钮拖拽还原功能,希望对大家有所帮助

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

相关文章:

验证码:
移动技术网