Lua learning notes: 2 Android calls Lua. Add a button in the Lua script and add a listener to the button.
Calls in Android
Try {mluastate. ldostring (readstream (getresources (). openrawresource (R. raw. test); // find the functioninluafile function mluastate. getfield (luastate. lua_globalsindex, "addbutton"); mluastate. pushjavaobject (getapplicationcontext (); // The first parameter contextmluastate. pushjavaobject (mlayout); // The second parameter, layoutmluastate. call (2, 0); // two parameters, 0 return values} catch (exception e) {e. printstacktrace ();}
Readstream implementation
Private string readstream (inputstream is) {try {bytearrayoutputstream BO = new bytearrayoutputstream (); int I = is. Read (); While (I! =-1) {Bo. write (I); I = is. read ();} return Bo. tostring ();} catch (ioexception e) {log. E ("readstream", "failed to read file stream"); Return "";}}
In the android project Res/raw/New Lua script testlua. Lua
-- Lua implementation method: Add a button, click the button, and toast displays the button title. Function addbutton (context, layout) BTN = luajava. newinstance ("android. widget. button ", context) BTN: settext (" Lua Add button ") -- first method: Listener implementation method button_cb = {onclick = function (v) print (tostring (v )) local toast = luajava. bindclass ('android. widget. toast ') toast: maketext (context, V: gettext (), toast. length_short): Show () end} Local listener = luajava. createproxy ("android. view. view $ onclicklistener ", button_cb); -- [[-- Method 2: Listener implementation method local listener = luajava. createproxy ("android. view. view $ onclicklistener ", {onclick = function (v) print (tostring (V) Local toast = luajava. bindclass ('android. widget. toast ') toast: maketext (context, V: gettext (), toast. length_short): Show () end})] -- BTN: setonclicklistener (listener) Layout: addview (BTN) End
I am not used to writing Lua scripts. I also add ";"
Finished