1. 程式人生 > >WebView和JS互調

WebView和JS互調

主函式:

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.webview)
    WebView webview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_html_call_java_);
        ButterKnife.bind(this);

        webview.loadUrl("file:///android_asset/test.html");

        webview.setWebChromeClient(new WebChromeClient());//使用的是Chrome瀏覽器,只有使用Chrome瀏覽器才可以彈出HTML中自己的對話方塊

        WebSettings settings = webview.getSettings();
        settings.setJavaScriptEnabled(true);

        //addJavascriptInterface(Object object, String name)
        webview.addJavascriptInterface(new MyObject(HTML_callJava_Activity.this),"myObj");
    }
}

佈局檔案:

    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </WebView>

MyObject:

public class MyObject {
    Context context;
    public MyObject(Context context) {
        this.context = context;
    }

    //該方法將會暴露給JavaScript呼叫
    @JavascriptInterface
    public void showToast(String name) {
        Toast.makeText(context, name + "你好", Toast.LENGTH_SHORT).show();
    }

    //該方法將會暴露給JavaScript呼叫
    @JavascriptInterface
    public void showList() {
        new AlertDialog.Builder(context)
                .setTitle("圖書列表")
                .setIcon(R.mipmap.ic_launcher)
                .setItems(new String[]{"java基礎", "Java高階進階", "java網路程式設計", "MYSQL與GUI", "JAVA專案實戰"}, null)
                .setPositiveButton("確定", null)
                .create()
                .show();
        ;
    }

}

test.html:

<!DOCTYPE html>
<html>

   <head>
    <meta http-equiv="Content-Type" content="text/html" charset="utf-8"/>
    <title>JS 呼叫Android(也可以說是js 呼叫Java)</title>

      <script   type="text/javascript">
         alert("你好好,我是HTML中彈出的對話方塊")
      </script>
   </head>


   <body>


   <!--注意此處的myObj 是Android暴露出來的物件-->
   <input
      type="button"
      value="打招呼"
      onclick="myObj.showToast('孫悟空');"
   />
   <input
           type="button"
           value="圖書列表"
           onclick="myObj.showList();"
   />

   </body>

</html>