当前位置: 移动技术网 > 移动技术>移动开发>Android > Android通过滑动实现Activity跳转(手势识别器应用)

Android通过滑动实现Activity跳转(手势识别器应用)

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

通过手势识别器实现界面的转跳,具体内容如下

1、创建 gesturedetector对象
2、创建新类继承simpleongesturelistener类(创建 gesturedetecto需要的参数)
3、重写simpleongesturelistener中的onfling()方法。(滑动手势监听)
4、重写界面的ontouchevent方法
5、通过 gesturedetector对象的ontouchevent()添加事件

代码如下:

public abstract class baseactivity extends appcompatactivity {

  private gesturedetector gue;

  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_base);
    //这里的第一个参数是上下文,第二个是手势监听器
    gue = new gesturedetector(this, new mygesturelistener());
  }

  class mygesturelistener extends gesturedetector.simpleongesturelistener {
//onfling方法的第一个参数是 手指按下的位置, 第二个参数是 手指松开的位置,第三个参数是手指的速度 

    @override
    public boolean onfling(motionevent e1, motionevent e2, float velocityx, float velocityy) {
      float startx = e1.getx();//通过e1.getx()获得手指按下位置的横坐标
      float endx = e2.getx();//通过e2.getx()获得手指松开位置的横坐标
      float starty = e1.gety();//通过e1.gety()获得手指按下位置的纵坐标
      float endy = e2.gety();//通过e2.gety()获得手指松开的纵坐标
      if ((startx - endx) > 50 && math.abs(starty - endy) < 200) {
      //(startx - endx) > 50 是手指从按下到松开的横坐标距离大于50
      // math.abs(starty - endy) < 200 是手指从按下到松开的纵坐标的差的绝对值

        //在这里通过intent实现界面转跳
      }

      if ((endx - startx) > 50 && math.abs(starty - endy) <200) {
        //在这里通过intent实现界面转跳
      }
//返回值是重点:如果返回值是true则动作可以执行,如果是flase动作将无法执行
      return true;
    }
  }

  @override
  public boolean ontouchevent(motionevent event) {
    gue.ontouchevent(event);
    return super.ontouchevent(event);
  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网