我没有在OnTouchListners中获得按钮释放吐司

问题描述

问题是我没有得到Button发布Toast。 我在xml中有一个简单的视图,即时通讯在该视图上执行onTouch。

hidenBtn.setonTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v,MotionEvent event) {
                    int action = event.getActionMasked();
                    if (action == MotionEvent.ACTION_DOWN) {
                        firstTime=System.currentTimeMillis();
                        Toast.makeText(MainActivity.this,"pressed",Toast.LENGTH_SHORT).show();
    
                    } else if (action == MotionEvent.ACTION_UP
                            || action == MotionEvent.ACTION_CANCEL) {
                        Toast.makeText(MainActivity.this,"Released",Toast.LENGTH_SHORT).show();
                        secondTime=System.currentTimeMillis();
                        if(secondTime-firstTime>=5000){
                            //do your actions here,prev,curr are fields in a class
                            ShowDialog();
                        }
                        else{
                            firstTime=0;
                            secondTime=0;
                        }
                    }
                    // Todo Auto-generated method stub
                    return false;
                }
            });

解决方法

像这样更改您的OnTouchListener

hidenBtn.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v,MotionEvent event) {
            int action = event.getActionMasked();
            if (action == MotionEvent.ACTION_DOWN) {
                firstTime=System.currentTimeMillis();
                Toast.makeText(MainActivity.this,"Pressed",Toast.LENGTH_SHORT).show();
                return true;
            } else if (action == MotionEvent.ACTION_UP
                    || action == MotionEvent.ACTION_CANCEL) {
                Toast.makeText(MainActivity.this,"Released",Toast.LENGTH_SHORT).show();
                secondTime=System.currentTimeMillis();
                if(secondTime-firstTime>=5000){
                    //do your actions here,prev,curr are fields in a class
                    ShowDialog();
                }
                else{
                    firstTime=0;
                    secondTime=0;
                }
            }
            // TODO Auto-generated method stub
            return false;
        }
    });

您将在false返回ACTION_DOWN,这意味着您没有消耗触摸事件,因此不会触发同一事件的其他步骤。因此,您需要在true中返回ACTION_DOWN,以便可以拦截ACTION_UP