2012-05-06 51 views
24

我想从我的webview中的一个JavaScript界面​​开始一个活动。 这个例子显示了一个敬酒。我怎么能称呼一个类而不是敬酒?在android webview中使用javascript

public class JavaScriptInterface { 
Context mContext; 

/** Instantiate the interface and set the context */ 
JavaScriptInterface(Context c) { 
    mContext = c; 
} 

/** Show a toast from the web page */ 
public void showToast(String toast) { 
    Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show(); 
} 
} 

这是html页面。

<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" /> 

<script type="text/javascript"> 
function showAndroidToast(toast) { 
    Android.showToast(toast); 
} 

+3

我没有足够的经验来回答,但你有没有读过:http://developer.android.com/guide/webapps/webview.html#UsingJavaScript – JaredMcAteer

+0

我已经做到了。 – Common

+0

好吧我只是没有看到任何地方,你在web视图中启用JavaScript,但它是相关的。 – JaredMcAteer

回答

60

你必须先登记您的WebView的JavaScriptInterface。 JavaScriptInterFace可以是一个内部类,如下所示。这个类将有一个函数,你可以从html页面调用(通过javaScript),在这个函数中你可以编写代码来改变活动。

这里是你工作的解决方案:

public class JavascriptInterfaceActivity extends Activity { 
    /** Called when the activity is first created. */ 


    WebView wv; 

    JavaScriptInterface JSInterface; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     wv = (WebView)findViewById(R.id.webView1); 

     wv.getSettings().setJavaScriptEnabled(true); 
     // register class containing methods to be exposed to JavaScript 

     JSInterface = new JavaScriptInterface(this); 
     wv.addJavascriptInterface(JSInterface, "JSInterface"); 

     wv.loadUrl("file:///android_asset/myPage.html"); 

    } 


    public class JavaScriptInterface { 
     Context mContext; 

     /** Instantiate the interface and set the context */ 
     JavaScriptInterface(Context c) { 
      mContext = c; 
     } 

     @android.webkit.JavascriptInterface 
     public void changeActivity() 
     { 
      Intent i = new Intent(JavascriptInterfaceActivity.this, nextActivity.class); 
      startActivity(i); 
      finish(); 
     } 
    } 
} 

下面是HTML页面

<html> 
<head> 
<script type="text/javascript"> 
function displaymessage() 
{ 
JSInterface.changeActivity(); 
} 
</script> 
</head> 

<body> 
<form> 
<input type="button" value="Click me!" onclick="displaymessage()" /> 
</form> 
</body> 
</html> 

希望这有助于...

+0

谢谢我的朋友。它几乎帮助我解决了我的问题。 – Common

+0

@常见我应该把上面的html代码放在单独的html文件中? –

+4

这对从JavaScript调用android函数很有用,但是有什么方法可以从android代码调用javascript函数? –

18

您还需要添加@android .webkit.JavascriptInterface您的android代码中的changeActivity方法之上的注释应该在Android 4.2或更高版本上运行。 有关更多信息,请参阅此link

+0

对于上述答案的附加信息非常有用! – David

+0

你先生是天才 – ashutosh

+0

它真的帮我 – vm345