Mattias Kamiński
Mattias Kamiński

Reputation: 33

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. 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.

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();
            }
        };
    });
}

Upvotes: 2

Views: 2820

Answers (2)

Don't reinvent the wheel Android has a

setOnLongClickListener()

That you can subscribe to and so detect that long press that you are looking for..

The doc is here

Upvotes: 4

JDC
JDC

Reputation: 4385

I would just use the method setOnLongClickListener():

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

Upvotes: 3

Related Questions