从HTML按钮调用Android活动方法

时间:2014-03-19 10:01:41

标签: android html

我试图在html按钮中调用一个java方法,在webView中加载,但是当我点击按钮时没有任何反应。这是我试过的代码

这是html代码

 <button onClick="activity.TestMethod();">Call Java Activity Method</button>

这是android活动方法

public void TestMethod()
  {
     Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)",
     Toast.LENGTH_LONG).show(); 

  }

我已使用

启用了JavaScript
 WebView index = (WebView) findViewById(R.id.webView1);
 WebSettings webSettings = index.getSettings(); 
 webSettings.setJavaScriptEnabled(true);
 index.loadUrl("file:///android_asset/index.html");

2 个答案:

答案 0 :(得分:6)

  

Activity.java文件

final MyJavaScriptInterface myJavaScriptInterface = new MyJavaScriptInterface(
                    this);
            webView.addJavascriptInterface(myJavaScriptInterface, "activity");

public class MyJavaScriptInterface {
        Context mContext;

    MyJavaScriptInterface(Context c) {
        mContext = c;
    }

    //Add @JavascriptInterface to call this method from > 4.2 Android Version
    @JavascriptInterface
    public void TestMethod() {

        Toast.makeText(mContext, "Hello from JavaScript Interface", Toast.LENGTH_SHORT).show(); 
    }
}
  

HTML文件

 <button onClick="jsMethod();">Call Java Activity Method</button>

<script type="text/javascript">
   function jsMethod(){
       activity.TestMethod();
    }
</script>

答案 1 :(得分:0)

您必须先为JavaScriptInterface设置WebView。有关示例,请参阅here