masmic masmic - 3 months ago 16
Android Question

Run continuous action when button is pressed

I'm trying to do this. When I touch a button and I keep pressing on it, it must perform an action, and this action will only stop when I stop pressing it.

To achieve this, I got this code:

btn_gas.setOnTouchListener(new OnTouchListener() {
private Handler mHandler;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (mHandler != null) return true;
mHandler = new Handler();
mHandler.postDelayed(mAction, 10);
break;
case MotionEvent.ACTION_UP:
if (mHandler == null) return true;
mHandler.removeCallbacks(mAction);
mHandler = null;
break;
}
return false;
}
Runnable mAction = new Runnable() {
@Override
public void run() {
// Do continuous task.
mHandler.postDelayed(this, 100);
}
};
});


But it isn't working as expected i.e. it performs the action continuously when I click on the button, even without me pressing on it continuously. To stop the action, I had to touch the button again.

How can I achieve the functionality I need?

Answer

Your logic for when you return true and false are reversed. Return true if you want to get future events, the ACTION_UP in this case. In fact, for a button you should be safe always returning true. Also, you do not need to keep reallocating your Handler.

   private Handler mHandler = new Handler ();
    btn_gas.setOnTouchListener(new OnTouchListener() {

    @Override
        public boolean onTouch(View v, MotionEvent event) {
        switch(event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mHandler.postDelayed(mAction, 10);
                break;
            case MotionEvent.ACTION_UP:
                mHandler.removeCallbacks(mAction);
                break;
        }

        return true;

    }
    Runnable mAction = new Runnable() {
        @Override
        public void run() {
            // Do continuous task.
            mHandler.postDelayed(this, 100);
        }
    };
});`
Comments