Skip to content

hanks-zyh/luaDevAndroid

Repository files navigation

做移动端开发,做蛋疼的就是不能动态发版,不能像 web 那样发版立即全部用户生效,然而 lua语言 为其提供了可能性。使用 lua 来构建跨平台原生应用有许多好处,比如 lua 语言简洁高效,可移植性好, Lua虚拟机极为轻量,仅占用200到300k的内存空间,且速度极快。

演示

写一个简单的代码演示一下。新建一个 lua 文件,叫做 view.lua, 放在手机的 sdcard 上,文件目录为 /sdcard/view.lua

require "import"
import "android.widget.*"
import "android.content.*"

function getView()
    local layout = {
        LinearLayout,
        orientation = "vertical",
        layout_width = "fill",
        layout_height = "fill",
        {
            Button,
            id = "btn",
            layout_marginTop="8dp",
            layout_width = "fill",
            layout_height = "50dp",
            text = "click"
        },
    }
    local view = loadlayout(layout)
    return view
end

运行一下,

屏幕中上半部分是 Android 的 xml 布局中写好的代码,当点击运行按钮时,加载 lua 脚本,返回一个 View 对象,然后添加到布局中。一个简单的 lua 脚本编写的视图就写好了。 接下来修改一下,设置个点击事件。

require "import"
import "android.widget.*"
import "android.content.*"

function getView()
    local layout = {
        LinearLayout,
        orientation = "vertical",
        layout_width = "fill",
        layout_height = "fill",
        {
            Button,
            id = "btn",
            layout_marginTop="8dp",
            layout_width = "fill",
            layout_height = "50dp",
            text = "click"
        },
    }
    local ids = {} -- store ids to find view
    local view = loadlayout(layout, ids)