本文共 2502 字,大约阅读时间需要 8 分钟。
【实例简介】
androlua 使用示例框架
【实例截图】
【核心代码】
public class MainActivity extends Activity {
// Lua解析和执行由此对象完成
private LuaState mLuaState;
// 用于演示,显示数据
private TextView mDisplay;
// 用于演示
private LinearLayout mLayout;
private Button button1;
private Button button2;
private Button button3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1 = (Button) findViewById(R.id.statemanet);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
runStatement(arg0);
}
});
button2 = (Button) findViewById(R.id.file);
button2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
runFile(arg0);
}
});
button3 = (Button) findViewById(R.id.callAndroid);
button3.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
callAndroidAPI(arg0);
}
});
mLayout = (LinearLayout) findViewById(R.id.layout);
mDisplay = (TextView) mLayout.findViewById(R.id.display);
mLuaState = LuaStateFactory.newLuaState();
mLuaState.openLibs();
}
public void runStatement(View v) {
// 定义一个Lua变量
mLuaState
.LdoString(" varSay = 'This is string in lua script statement.'");
// 获取
mLuaState.getGlobal("varSay");
// 输出
mDisplay.setText(mLuaState.toString(-1));
}
public void runFile(View v) {
mLuaState.LdoString(readStream(getResources().openRawResource(
R.raw.test)));
// 找到functionInLuaFile函数
mLuaState.getField(LuaState.LUA_GLOBALSINDEX, "functionInLuaFile");
// 将参数压入栈
mLuaState.pushString("从Java中传递的参数");
// functionInLuaFile函数有一个参数,一个返回结果
int paramCount = 1;
int resultCount = 1;
mLuaState.call(paramCount, resultCount);
// 将结果保存到resultKey中
mLuaState.setField(LuaState.LUA_GLOBALSINDEX, "resultKey");
// 获取
mLuaState.getGlobal("resultKey");
// 输出
mDisplay.setText(mLuaState.toString(-1));
}
public void callAndroidAPI(View v) {
mLuaState.LdoString(readStream(getResources().openRawResource(
R.raw.test)));
// 找到functionInLuaFile函数
mLuaState.getField(LuaState.LUA_GLOBALSINDEX, "callAndroidApi");
mLuaState.pushJavaObject(getApplicationContext());
mLuaState.pushJavaObject(mLayout);
mLuaState.pushString("设置到TextView的数据");
mLuaState.call(3, 0);
}
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 "";
}
}
参考:
http://my.oschina.net/chenyoca/blog/69169
转载地址:http://mlnuo.baihongyu.com/