Android使用OnTouch检测longClick位置

时间:2018-07-02 22:24:16

标签: android ontouchlistener

好吧,我的目标是检测长点击的位置,我很困惑从何处开始,但是我尝试使用OnTouch,因为它有助于检测点击的位置,我试图使用计时器使它作为longClick运行,但是不会

clickableObject.setOnTouchListener(new View.OnTouchListener() {
            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if(motionEvent.getAction()==MotionEvent.ACTION_DOWN){
                    if(!hold)startTime=System.currentTimeMillis();
                }
                else if(motionEvent.getAction()==MotionEvent.ACTION_UP){
                    hold=false;
                }
                while(motionEvent.getAction()==MotionEvent.ACTION_DOWN&&System.currentTimeMillis()-startTime<=1500);
                if(System.currentTimeMillis()-startTime>1500)
                    Toast.makeText(context, "done", Toast.LENGTH_SHORT).show();
                return true;
            }
        });
/*

就像我单击快捷键一样,它只希望在longClick上起作用

2 个答案:

答案 0 :(得分:0)

更简单的方法:

clickableObject.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            Toast.makeText(context, "done", Toast.LENGTH_SHORT).show();
            return true;
        }
    });

答案 1 :(得分:0)

最后我找到了解决方案 我在OnTouch中使用longClick侦听器创建了onTouchListener,我只获得位置

在OnLongListener中,我使用位置值

@SuppressLint("ClickableViewAccessibility")
    public void getClickPositions(View clickableObject, final ClickPositions clickPositions){
        clickableObject.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if(motionEvent.getAction()==MotionEvent.ACTION_DOWN) {
                    if (clickPositions != null)
                        clickPositions.getLastCordination(motionEvent.getX(), motionEvent.getY());
                }
                return false;
            }
        });

    }

public interface ClickPositions{void getLastCordination(float left,float top);}

public void showImageOptions(final View clickableObject, final ClickPositions clickPositions) {
        getClickPositions(clickableObject, new ClickPositions() {
            @Override
            public void getLastCordination(float left, float top) {
                x = left;
                y = top;
            }
        });
        clickableObject.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                Toast.makeText(context, String.valueOf(x) + ",", Toast.LENGTH_SHORT).show();
                return false;
            }
        });
    }

然后我仅调用函数showImageOption