package com.vimi8.app.activity; import android.content.Context; import android.os.Bundle; import android.view.KeyEvent; import android.webkit.JavascriptInterface; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; import com.vimi8.app.R; import com.vimi8.app.framework.ActivityBase; /** * Created by vimi8 on 2017/4/18. */ public class YyxText extends ActivityBase { private WebView myWebView ; @Override protected void initVariables(Bundle savedInstanceState) { } @Override protected int initLayoutViews() { return R.layout.yyx_text; } @Override protected void initViewsAndStaticData() { //獲取webview控件 myWebView = (WebView) findViewById(R.id.web_view); //加載服務器上的頁面 myWebView.loadUrl("http://www.baidu.com"); //加載本地中的html //myWebView.loadUrl("file:///android_asset/www/test2.html"); //加上下面這段代碼可以使網頁中的鏈接不以瀏覽器的方式打開 myWebView.setWebViewClient(new WebViewClient()); //得到webview設置 WebSettings webSettings = myWebView.getSettings(); //允許使用javascript webSettings.setJavaScriptEnabled(true); //將WebAppInterface於javascript綁定 myWebView.addJavascriptInterface(new WebAppInterface(this), "Android"); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) { myWebView.goBack(); return true; } return super.onKeyDown(keyCode, event); } public class WebAppInterface { Context mContext; /** Instantiate the interface and set the context */ WebAppInterface(Context c) { mContext = c; } /** Show a toast from the web page */ @JavascriptInterface public void showToast(String toast) { Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show(); } }
}
下面是HTML代碼
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" /> 這裏調用android中的方法 <script type="text/javascript"> function showAndroidToast(toast) { Android.showToast(toast); }