【问题标题】:Creating an interface in Android在 Android 中创建界面
【发布时间】:2011-07-29 01:44:13
【问题描述】:

有人可以指导我完成此操作的最佳方法吗?我想做一个扩展OnTouchListener 的接口。而不是一个叫onTouch(View view, MotionEvent e)的肉食,我想要3个肉食; onPress()onMove()onRelease()。当您在屏幕上按下时,onPress 会被调用,当您在屏幕上移动手指时,onMove 会被调用。 onRelease 在您松开手指时被调用。欢迎所有相关答案。

【问题讨论】:

标签: java android interface ontouchlistener


【解决方案1】:

您可以通过扩展您的View 类并向该类添加setYourTouchListener(YourTouchListener listener) 方法来使用duffymo 提供的YourTouchListener

然后,您将覆盖 onTouchEvent(MotionEvent event) 并调用侦听器的相关方法。像这样:

public boolean onTouchEvent(MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            listener.onPress(this, event);
            break;
        case MotionEvent.ACTION_MOVE:
            listener.onMove(this, event);
            break;
        case MotionEvent.ACTION_UP:
            listener.onRelease(this, event);
            break;
    }
    //this means that you have "used" this event. The ViewGroup will direct all further associated events straight here.
    return true;
}

【讨论】:

  • @parkovski 有一个很好的观点 - 与其扩展 OnTouchListener,不如使用您想要的方法创建您自己的界面。
【解决方案2】:

我可能会按照 CaspNZ 发布的内容进行操作,唯一的区别是在这种情况下您不应该扩展 OnTouchListener。实现一个接口意味着您必须为它的 所有 方法提供一个实现,因此在这种情况下,onTouch 除了您正在创建的三个方法之外,这是多余的。当然,如果您最终仍然需要 onTouch 做某事,除了 YourTouchListener 之外,您还可以随时实现 OnTouchListener

【讨论】:

    【解决方案3】:

    您可以使用GestureListeneronFling(...) 方法,这使您可以(MotionEvent e1MotionEvent e2)测量初始触摸(按下时)和最终触摸(释放),并在此基础上执行您的操作工作。还提供沿 xy 轴的 velocityMotionEvent,测量施加在屏幕上的压力等。这将减少您编写整个界面的时间即将做。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-31
      • 2019-09-23
      相关资源
      最近更新 更多