简体   繁体   中英

set button pressed and keep executing same task in Android

I am currently doing my little project. I want to simply set 4 buttons in my APP and by pressing the button, I should keep doing the same thing till I release the button. ( For example, I need to use these 4 buttons to control my machine's direction.)

I've been trying few different methods, such as onTouch. However, In this method, I need to keep slightly move my finger so that I can keep doing the same thing. otherwise, it will stop. Also for onlongClicklistener and setpressed to true. None of them have the thing I want.

Can anyone tell me what methods I can call or the logic to implement this? Thank you so much! :)

you can set the normal on click listener and inside start a thread, timer, backgroundtask, or something else that would periodically check if your button is pressed.

For example you could do it similarly to this:

final Button yourButton = (Button) view.findViewById(R.id.your_button);
long timerInterval = 1000; //one second
yourButton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        final Timer t = new Timer();
        t.scheduleAtFixedRate(new TimerTask() {
            public void run() {
                if (yourButton.isPressed()) {
                    // do something (executing your code on button being pressed)
                } else {
                    t.cancel();
                }
            }
        }, 0, timerInterval);
    }
});

This will execute your code every second the button is being pressed.

IMPORTANT: This presents the general idea, remember that the anonymous TimerTask class will hold a strong reference to the yourButton instance which is a subject to leak. You should be using a your_button reference that will be "garbage-collected" if the View is destroyed and inside the TimerTask you should be checking if yourButton is null or not.

I think onTouchListerner will best suits for your requirement. Use thread for doing the work. On event ACTION_DOWN start the thread and on event ACTION_UP stop the thread.

((Button) findViewById(R.id.leftBtn)).setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View arg0, MotionEvent event) {
            if(event.getAction() == MotionEvent.ACTION_DOWN){
                // start the thread
                return true;
            } else if(event.getAction() == MotionEvent.ACTION_UP){
                // stop the thread
                return true;
            }
            return false;

        }
    });

Hope this will help for you.

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