检测自定义视图的长按?

Orb*_*bit 9 android android-custom-view android-view

我有一个扩展FrameLayout和实现的自定义视图ScaleGestureDetector.OnScaleGestureListener.正如类名所示,此视图是可缩放的+可扩展的.下面是自定义视图类:https://gist.github.com/Orbyt/23c82ce9002df6c318d4

我一直试图找到一种方法来检测此视图的长按.我知道,通常,我可以在Activity中做这样的事情:

GestureDetector mGestureDetector = new GestureDetector(this, this);

mZoomableLayout.setOnTouchListener(new View.OnTouchListener()
{
    @Override
    public boolean onTouch(View v, MotionEvent event)
    {
        return mGestureDetector.onTouchEvent(event);
    }
});

mGestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener()
{
    @Override
    public void onLongPress(MotionEvent e)
    {
      // do tasks here
    }
});
Run Code Online (Sandbox Code Playgroud)

使用它,View不再可缩放,大概是因为它拦截了所有onTouch事件而不是Views类中的实现.

所以我的问题是,检测此视图的长按是什么最干净的方法?

Ale*_*ona 1

好吧,抱歉我根本不明白你的问题。现在在您的 MainActivity 中:

public yourMainConstructor()
{
  [...]

  GestureDetector sgd;
  sgd = new GestureDetector(context,new ScaleListener());

  [...]
}

class ScaleListener extends GestureDetector.SimpleOnGestureListener {

    @Override
    public void onLongPress(MotionEvent e) {

        super.onLongPress(e);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在你的主类中重写 onTouchEvent()

@Override
public boolean onTouchEvent(MotionEvent event) 
{
    sgd.onTouchEvent(event);

    switch (event.getAction()) 
    {
        case MotionEvent.ACTION_DOWN:
        [...]
    }
}
Run Code Online (Sandbox Code Playgroud)