Continuously increase integer value as the button is pressed

后端 未结 9 1283
长情又很酷
长情又很酷 2020-12-04 11:10

I\'m new to Android so sorry if the question is easy to answer. I have two buttons, a decrease and an increase button, and in the middle of them a TextView which displays a

9条回答
  •  离开以前
    2020-12-04 11:24

    Just wanna share my own solution that worked out for me really well.

    First, create a handler in your activity

    private Handler mHandler = new Handler();
    

    Then, create the runnables that will increment/decrement and display your number. In here, we will check if your button is still in its pressed state and increment then re-run the runnable if it is.

    private Runnable incrementRunnable = new Runnable() {
        @Override
        public void run() {
            mHandler.removeCallbacks(incrementRunnable); // remove our old runnable, though I'm not really sure if this is necessary
            if(IncrementButton.isPressed()) { // check if the button is still in its pressed state
                // increment the counter
                // display the updated value here, if necessary
                mHandler.postDelayed(incrementRunnable, 100); // call for a delayed re-check of the button's state through our handler. The delay of 100ms can be changed as needed.
            }
        }
    }
    

    Finally, use it in our button's onLongClickListener

    IncrementButton.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View view) {
            mHandler.postDelayed(incrementRunnable, 0); // initial call for our handler.
            return true;
        }
    });
    

    That's it!


    Another way of doing it is declaring both the handler and runnable inside the OnLongClickListener itself although I myself am not sure if this is a good practice.

    IncrementButton.setOnLongClickListener(new View.OnLongClickListener() {
        private Handler mHandler = Handler();
        private Runnable incrementRunnable = new Runnable() {
            @Override
            public void run() {
                mHandler.removeCallbacks(incrementRunnable);
                if(IncrementButton.isPressed()) {
                    // increment the counter
                    // display the updated value here, if necessary
                    mHandler.postDelayed(incrementRunnable, 100);
                }
            }
        };
    
        @Override
        public boolean onLongClick(View view) {
            mHandler.postDelayed(incrementRunnable, 0);
            return true;
        }
    });
    

    When doing this continuous increment, I would suggest to increase the increment value after a certain time/number of increments. E.g. If the number_of_increment made is less than 10, we increment by 1. Otherwise, we increment by 3.

提交回复
热议问题