创建一个带webview控件的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:id="@+id/webview" android:layout_width="match_parent" android:layout_height="match_parent"/> </RelativeLayout>在assets中创建一个html文件
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> this is html </body> </html>
在activity中加载html
public class MainActivity extends Activity { private WebView webview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); webview = (WebView) findViewById(R.id.webview); webview.loadUrl("file:///android_asset/NewFile.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.main, menu); return true; } }
添加webview对js的支持
public class MainActivity extends Activity { private WebView webview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); webview = (WebView) findViewById(R.id.webview); webview.getSettings().setJavaScriptEnabled(true);//支持对js的使用 webview.loadUrl("file:///android_asset/NewFile.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.main, menu); return true; } }
public class JavaScriptObject{ @JavascriptInterface public void ToastString(String toast){ Toast.makeText(MainActivity.this, toast, Toast.LENGTH_LONG).show(); } @JavascriptInterface public String toHtmlJson(){ return "json to json"; } }
webview.addJavascriptInterface(new JavaScriptObject(), "JS");
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <a id="text">this is html</a> <input type="button" id="btn" value="Toast"/> <script> var btn = document.getElementById('btn'); btn.addEventListener('click',function(){ JS.ToastString("这是从html传入的数据"); return false; },false); </script> </body> </html>
在html获取android传来的数据
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <a id="text" onclick="setText()">this is html</a> <input type="button" id="btn" value="Toast" /> <script> var json = JS.toHtmlJson(); var btn = document.getElementById('btn'); btn.addEventListener('click', function() { JS.ToastString("这是从html传入的数据"); return false; }, false); function setText() { document.getElementById('text').innerHTML = json; } </script> </body> </html>