简体   繁体   English

处理程序删除回调,然后再次放入ACTION_UP

[英]Handler remove callback and put again in ACTION_UP

I want to call function(close one widget if user didn't touch another view for 10 seconds). 我想调用函数(如果用户在10秒钟内未触摸另一个视图,则关闭一个窗口小部件)。 Touchable view has listener like 可触摸的视图具有听众喜欢

@Override
public boolean onTouchEvent(MotionEvent event) {
    int x = (int) event.getX();
    int y = (int) event.getY();
    switch (event.getAction()) {

    case MotionEvent.ACTION_MOVE:
        if(handler != null){
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
        break;
    case MotionEvent.ACTION_DOWN:
        if(handler != null){
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
        break;
    case MotionEvent.ACTION_UP:
        startTime = Calendar.getInstance().get(
                        Calendar.MILLISECOND);
                handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        isMenuVisible = false;
                        postInvalidate();
                    }
                }, startTime + EXPANDED_PERIOD);
        break;
    }
    return true;
}

I have tried also to have only one member handler and to avoid to create on up. 我也尝试过只有一个成员处理程序,并避免创建起来。 Idea is when user do up action to wait 10 seconds if not touch again and then close. 想法是,如果用户没有再触摸然后再关闭,则应进行10秒钟的操作。 But it doesn't close. 但这并没有关闭。 When I remove in ACTION_DOWN and ACTION_MOVE remove it closes even when I touch view. 当我在ACTION_DOWN和ACTION_MOVE删除中删除时,即使我触摸视图也将关闭。 How to solve this ? 如何解决呢?

You should not add startTime in postDelayed() 您不应该在postDelayed()中添加startTime

Read doc here. 在此处阅读文档。

use the following code instead. 请改用以下代码。

handler.postDelayed(***, EXPANDED_PERIOD);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM