简体   繁体   中英

Button with OnTouchListener that continuously does something while held down in Android Studio

I am a noob to Android Studio, but am creating an application for a class for school. It is a max bench press calculator. I would like to make it so that when the increase or decrease weight button is held down, then the weight will continuously go up or down. I saw a couple of questions on this, but they were very confusing and weren't very well explained. I would rather not put code in that I don't know how it works, just to make the application run. Thanks!!

You can achieve such an effect by creating the button then setting it's onTouchListener to call certain methods when certain types of touch events are detected on the button. For example:

increaseWeightButton.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View view, MotionEvent mEvent) {
        if (mEvent.getAction() == MotionEvent.ACTION_DOWN)
            startIncreasingWeight();
        else if (mEvent.getAction() == MotionEvent.ACTION_UP)
            stopIncreasingWeight();
        return false;
    }
});

edit: Can you try putting the button.setOnTouchListener code just after creating the button in the onCreate() rather than outside?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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