我们如何在android中增加按钮长按监听时间?

问题描述 投票:0回答:2

我想在同一个按钮上执行简单的点击监听器以及长按监听器。但是我需要在持续1秒钟后执行longclicklistener延迟5秒后执行长时间点击监听器。所以使用处理程序它将在5次seocnds之后执行。但我需要完全按下按钮5秒然后代码执行...

android android-studio android-button
2个回答
1
投票

你可以像这样使用Handler

Button b=findViewById(R.id.btn);

    final Runnable run = new Runnable() {

        @Override
        public void run() {
            Toast.makeText(MainActivity.this, "clicked", Toast.LENGTH_SHORT).show();
            // Your code to run on long click

        }
    };
    final Handler handel = new Handler();
    b.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View arg0, MotionEvent arg1) {
            switch (arg1.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    handel.postDelayed(run, 5000/* OR the amount of time you want */);
                    break;

                default:
                    handel.removeCallbacks(run);
                    break;

            }
            return true;
        }
    });

1
投票

无法在onLongClick事件上更改计时器,它由android本身管理。

可能的是使用.setOnTouchListener()。

然后在MotionEvent是ACTION_DOWN时注册。注意变量中的当前时间。然后当注册带有ACTION_UP的MotionEvent并且current_time - actionDown时间> 5000 ms然后执行某些操作。

非常好:

Button button = new Button();
long then = 0;
    button.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if(event.getAction() == MotionEvent.ACTION_DOWN){
                then = (Long) System.currentTimeMillis();
            }
            else if(event.getAction() == MotionEvent.ACTION_UP){
                if(((Long) System.currentTimeMillis() - then) > 5000){
                    // 5 second of long click
                    return true;
                }
            }
            return false;
        }
    })
© www.soinside.com 2019 - 2024. All rights reserved.