简体   繁体   English

Android按住按钮几秒钟,然后执行某些操作

[英]Android hold button for few seconds and then do something

I want to make button which does something when is hold for 3 seconds and I got this. 我想制作一个按钮,在按住3秒钟时它会执行某些操作,然后我知道了。 It does work but I wonder if its correct way of doing things, what I mean by that that I want to make all buttons designed same way, whole menu based on hold for x seconds and then proceed with something and I wonder if it wont make problems and wont make my app laggy. 它确实可以工作,但是我想知道它是否是正确的工作方式,这是什么意思,我想使所有按钮都以相同的方式设计,整个菜单基于按住x秒钟,然后继续执行某些操作,所以我想知道它是否会成功问题,不会让我的应用程序落后。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    onbutton = (Button)findViewById(R.id.onbutton);
    onbutton.setOnTouchListener(new View.OnTouchListener() {
        private Handler handler;
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            switch(motionEvent.getAction()){
                case MotionEvent.ACTION_DOWN:
                    onbutton.setBackgroundResource(R.drawable.onbuttonshape);
                    handler = new Handler();
                    handler.postDelayed(run,3000);
                    break;
                case MotionEvent.ACTION_UP:
                    onbutton.setBackgroundResource(R.drawable.buttonshape);
                    handler.removeCallbacks(run);
                    break;
            }
            return true;
        }
        Runnable run = new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MainActivity.this, "delayed msg", Toast.LENGTH_SHORT).show();
            }
        };
    });
}

Don't reinvent the wheel Android has a 不要重新发明Android的功能

setOnLongClickListener()

That you can subscribe to and so detect that long press that you are looking for.. 您可以订阅,因此可以检测到您正在寻找的长按

The doc is here 该文档在这里

I would just use the method setOnLongClickListener() : 我只会使用setOnLongClickListener()方法:

button.setOnLongClickListener(new OnLongClickListener() { 
    @Override
    public boolean onLongClick(View v) {
        // Do what you want to do atfer a long click here
        return true;
    }
});

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

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