gpt4 book ai didi

android - 检测自定义 View 上的长按?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:38:10 24 4
gpt4 key购买 nike

我有一个扩展 FrameLayout 并实现 ScaleGestureDetector.OnScaleGestureListener 的自定义 View 。正如类名所暗示的那样,这个 View 是可缩放 + 可平移的。这是自定义 View 类:https://gist.github.com/Orbyt/23c82ce9002df6c318d4

我一直在努力寻找一种方法来检测对此 View 的长按。我知道,通常我可以在 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
}
});

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

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

最佳答案

我有一个捏缩放圆圈,我在上面检测到正常点击和长按。下面给出了代码 fragment 。在此,我通过 MotionEvent.ACTION_DOWN 和 MotionEvent.ACTION_UP 之间的时间间隔检测到长按和正常点击。

希望对您有所帮助。

     private static final int MAX_CLICK_DURATION = 200;
private float mScaleFactor = 1.0000000f;
private long mStartClickTime;


@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
boolean right = x > (screenWidthPX / 2 + ((mLayoutHeight / 4) + 20) * mScaleFactor);
boolean left = x < (screenWidthPX / 2 - ((mLayoutHeight / 4) + 20) * mScaleFactor);
boolean top = y > (mLayoutHeight / 2 + ((mLayoutHeight / 4) + 20) * mScaleFactor);
boolean bottom = y < (mLayoutHeight / 2 - ((mLayoutHeight / 4) + 20) * mScaleFactor);


if (event.getPointerCount() > 1) {
if (left || right || top || bottom) {
// You may not need this condtion, I needed this because I had custom view of pinch zoom circle and, this condition detects the touch at outer area of circle.
} else {
mScaleGestureDetector.onTouchEvent(event);
}
} else {
switch (event.getAction()) {

case MotionEvent.ACTION_DOWN: {
mStartClickTime = Calendar.getInstance().getTimeInMillis();

break;
}
case MotionEvent.ACTION_UP: {
long clickDuration = Calendar.getInstance().getTimeInMillis() - mStartClickTime;

if (clickDuration < MAX_CLICK_DURATION) {
if (left || right || top || bottom) {

} else {
Toast.makeText(mContext, "Normal CLick Detected", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(mContext, "Long CLick Detected", Toast.LENGTH_SHORT).show();

}
}
}
}
return true;
}

关于android - 检测自定义 View 上的长按?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34670553/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com