These two days finally idle a bit, on the handy again quick pick up and learn to learn, always think quick than cocos2dx that set of LUA binding to a lot of convenience, 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 number--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 to the layer? An event listener, the type of event listener is keypad, assuming that the value of key is back then run the code inside, assuming there is no need to display Android Native dialog box, just to close the program, You just need to run the part of the stare in the code above.
The version number after 2.2.3 is different from the previous event listener, it needs to be noted 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 makes it very easy to invoke static functions 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!