1

How would I go about implementing a fast incrementation when I hold on a button in an Android Activity. So for example when I hold on a button, a number that I have already set in an EditText increases at a fast pace.

Your help would be most appreciated.

  • Go back to some of your previously asked questions and mark helpful answers as correct - asking a question and never rewarding the person who helped you won't get you very far. – mopsled Jul 22 '11 at 15:33

2 Answers2

0

Well, I would use a System.currentTimeMillis() inside the onTouch method. In the case TouchEvent.ACTION_DOWN: start the millis count (use your custom math function to use milliseconds) and stop the count in the TouchEvent.ACTION_UP.

Zappescu
  • 1,429
  • 2
  • 12
  • 25
0

You can extend the TimerTask class and override the "run" method with what you want to do. In this case, "run" would increment your EditText's text. Then just make a Timer and give it your overloaded TimerTask class.

Example:

import java.util.TimerTask;

public class MyTask extends TimerTask {
    private Integer mIncrement = 0;

    public MyTask() {
    }

    @Override
    public void run() {
        mIncrement++;

        // Then notify the GUI somehow (Maybe with a Handler)
    }
}

Now you just need to schedule "MyTask" to run when your button is down:

        mButton.setOnTouchListener(
            new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getPointerCount() > 0 && !mIncrementing) {
                        mIncrementing = true;
                        MyTask task = new MyTask();
                        mTimer = new Timer();
                        mTimer.scheduleAtFixedRate(task, 0, 10);
                    } else {
                        mIncrementing = false;
                        mTimer.cancel();
                    }
                    return true;
                }
            }
        );

I hope this helps. For more information, see the documentation on Timer: http://developer.android.com/reference/java/util/Timer.html

Also, you may notice you can't set your EditText's text value from within MyTask.run. This is because Android doesn't allow cross-thread access to GUI elements. To update your EditText, you need to pass a message with a Handler to tell the main thread to update its value.

Jim
  • 833
  • 6
  • 13