Android development, often encountered a demand, that is, the button long press to repeat an action, release and stop the execution of the action. Online to find a lot of code, there is no suitable, so I wrote a.
The basic idea is to first set an identity variable that identifies whether it is in the pressed state. When the button is pressed, set the identity variable to true to start a thread that repeats an action (when the identity variable is true, the loop executes the action, when false jumps out of the loop, ends the action), and when the button bounces, sets the identity variable to false.
1. First, set the identity variable
1 Private Boolean false ; 2 Private Button Rightsend;
2. Then, initialize the variable
protected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Rightsend=(Button) Findviewbyid (r.id.btnright); Longpress=false; Rightsend.setontouchlistener (NewView.ontouchlistener () {@Override Public BooleanOnTouch (View V, motionevent event) {String str= "ond\n"; String Strsenddata=NewString (str); Longtouchsendcmd (mainactivity. This, Strsenddata, event); Senddata.settext (""); return false; } } );}
2, then, the implementation of the button press repeated execution action
Private voidLongtouchsendcmd (FinalActivity activity,FinalString cmd, motionevent event) { if(Booleanconnect = =false) {Toast.maketext (activity,"Please connect the device first", Toast.length_short). Show (); return; } Switch(Event.getaction ()) { Casemotionevent.action_down: {longpress=true; Toast.maketext (activity,"Start Sending", Toast.length_short). Show (); Longpresssendcmdthread=NewThread () { Public voidrun () {Super. Run (); while(true) { if(Longpress = =true)//Long Press continuous Send command { Try {
//todo Some action adds code here, executes an action//string strsenddata = cmd; Connectedthread.write (Strsenddata.getbytes ());//Receive Data Thread.Sleep (1000);//1 seconds to send}Catch(interruptedexception e) {e.printstacktrace (); } }Else { Break;//no press, exit loop } } } }; Longpresssendcmdthread.start (); Break; } Casemotionevent.action_up:{longpress=false; Toast.maketext (activity,"End Send", Toast.length_short). Show (); } } }
Results of execution:
Android button Long press to repeat an action, release and then stop the action