我正在尝试从 html 页面实现 C 程序的语法突出显示。
"index.html","prettify.css","prettify.js"存放在assets文件夹中
这是我的 webview 的代码:
package com.example.javascriptexample;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.webkit.WebView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView wv=(WebView) findViewById(R.id.webView);
wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setDomStorageEnabled(true);
wv.loadUrl("file:///android_asset/index.html");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
对应的布局文件(XML)是:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<WebView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:id="@+id/webView" />
</RelativeLayout>
index.html如下:
<HTML>
<body>
<pre>
<code class="prettyprint">
/*---------- PROGRAM USING IF STATEMENT --------*/
#include < stdio.h >
#include < conio.h >
void main()
{
int count, i;
float weight, height;
count = 0;
printf("Enter weight and height for 10 boys\n");
for (i =1; i <= 10; i++)
{
scanf("%f %f", &weight, &height);
if (weight < 50 && height > 170)
count = count + 1;
}
printf("Number of boys with weight < 50 kg\n");
printf("and height > 170 cm = %d\n", count);
getch();
}
</code>
</pre>
<script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js"></script>
</body>
</HTML>
我尝试在互联网上搜索但无法解决这个问题。 文本正在显示但没有语法突出显示(即我在 webview 中实现 javascript 的方式可能有问题。 然而,脚本在我的电脑上运行顺利,所以也许我犯了一些错误,因为我是 javascript 和 android 的初学者。 btw,美化的css和js文件不是我写的,我是从网上下载的(code.google.com)
我经历了其他类似的问题。提供的解决方案之一是“你必须强制应用程序等待(尝试一下,在你的 webview 上放置一个断点,然后让它继续,你会看到这次 webview 将可靠地加载 javascript。而如果你只是让应用程序在没有断点的情况下加载,它经常“跳过”javascript)。需要某种强制线程等待方法。“
-如何实现?即,如何放置断点然后让它继续?
最佳答案
你写道你已经在 Assets 文件夹中存储了“prettify.css”,“prettify.js”, 但你没有使用它们。相反,您通过网络加载脚本,这可能会导致计时问题。
<script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js"></script>
要使用您的本地资源,请将以下链接添加到标题部分
<link href="prettify.css" type="text/css" rel="stylesheet" />
并用以下内容替换网络脚本标签
<script type="text/javascript" src="prettify.js"></script>
关于Javascript 不能始终在 android webview 上工作。有时它起作用,大多数时候它不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17641780/