These two days finally idle a bit, on the easy and quick pick up and learn to learn, has always felt quick than cocos2dx that set of LUA binding to facilitate a lot of, today tried the next Android Back button monitoring, or very good to get, so there is this article.
First explain the use of the quick version--2.2.5.
Directly on the code
function mainscene:addbackevent () if device.platform = = "Android" then Self.touchlayer = Display.newlayer () Self.touchLayer:addNodeEventListener (CC. Keypad_event, Function (EVENT) if Event.key = = "Back" and then --ccdirector:shareddirector (): Endtolua () Local javaclassname = "Com/cocos2dx/testgame/testgame" local javamethodname = "Exit" Luaj.callstaticmethod ( Javaclassname, Javamethodname) end end) self.touchLayer:setKeypadEnabled (True) Self:addchild ( Self.touchlayer) End End
Better understand, create a layer, add an event listener for this layer, this event listener type is keypad, if the value of key is back then execute the inside code, if you do not need to display the Android Native dialog box, just close the program, You just need to execute the part of the comment in the code above.
The version after 2.2.3 is different from the previous Add event listener, which needs attention here.
Of course, do the software, at least there is a warm hint, to prevent users from accidentally point to exit the game is not friendly, so here call the Android Native dialog box to display. Quick provides a luajavabridge for this sample, which can be easily called to a static function in Android.
Here's the code for the function called in Android.
public static void Exit () {Instance.runonuithread (new Runnable () {@Overridepublic void run () {Builder builder = new Builde R (instance); Builder.settitle ("hint"), Builder.setmessage ("OK Exit"); Builder.seticon (Android. R.drawable.ic_dialog_info); Builder.setpositivebutton ("OK", new Onclicklistener () {@Overridepublic void OnClick ( Dialoginterface dialog, int which) {system.exit (0);}}); Builder.setnegativebutton ("Cancel", new Onclicklistener () {@Overridepublic void OnClick (dialoginterface dialog, int which) {Dialog.dismiss ();}}). Show ();}});
That's it!