lua學習筆記: 2 android調用Lua。Lua指令碼中實現添加Button,並為Button增加Listener
android 中的調用
try {mLuaState.LdoString(readStream(getResources().openRawResource(R.raw.test)));// 找到functionInLuaFile函數mLuaState.getField(LuaState.LUA_GLOBALSINDEX, "addButton");mLuaState.pushJavaObject(getApplicationContext());// 第一個參數 contextmLuaState.pushJavaObject(mLayout);//第二個參數, LayoutmLuaState.call(2, 0);// 2個參數,0個傳回值} catch (Exception e) {e.printStackTrace();}
readStream 實現
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", "讀取檔案流失敗");return "";}}
在Android 工程 res/raw/建立lua指令碼 testLua.lua
-- lua 實現方法,增加一個Button,點擊Button, Toast顯示Button標題。function addButton(context,layout) btn = luajava.newInstance("android.widget.Button",context) btn:setText("lua add button ") -- 第一種方法Listener 實現方法 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);--[[ -- 第二種方法Listener實現方法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
寫Lua指令碼還不習慣,還按 c java 的習慣,在後面加";"
完畢