将您的 C 代码保存在 assets 文件夹中的文件中,例如“res/assets/code.c”。
编写一个将文件内容读取到字符串的函数:
private String readFileInAssetsDir(String filename) {
BufferedReader br = null;
StringBuffer sb = new StringBuffer();
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(filename)));
String line;
while((line = br.readLine()) != null)
sb.append(line + "\n");
} catch(Exception e) {
// TODO
}
return sb.toString();
}
而现在在你的布局中定义一个WebView(不是TextView)(优点是可以显示任何字符,WebView直接提供缩放和滚动):
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1" />
最后,我将所有 C 代码包含在一个<pre></pre>
标签中,然后在 WebView 小部件中显示它:
String plainCode = readFileInAssetsDir("code.c");
String htmlCode = "<pre>" + plainCode + "</pre>";
webView.loadDataWithBaseURL("", htmlCode, "text/html", "utf-8", "");