Android--WebView+HTML+Javascript

阅读更多
知识点:android的WebView控件加载HTML并通过js实现数据的交互

步骤一、主页面代码


    
    
      




步骤二、HTML+javascript代码


 
   New Document 
  
  
  
  
  
 

 
   
   我的姓名:

   


步骤三、MainActivity代码
package com.example.webviewdemo;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class MainActivity extends Activity {
	private WebView webView = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		webView = (WebView) findViewById(R.id.mywebView);

		webView.getSettings().setJavaScriptEnabled(true);

		webView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return true;
			}
		});
		webView.setWebChromeClient(new WebChromeClient(){

			@Override
			public boolean onJsAlert(WebView view, String url, String message,
					JsResult result) {
				// TODO Auto-generated method stub
				return super.onJsAlert(view, url, message, result);
			}
			
		});
		webView.getSettings().setDefaultTextEncodingName("gbk");
		webView.addJavascriptInterface(new myinterface(this) , "myobj");
		webView.loadUrl("file:///android_asset/myname.html");
	//	webView.loadDataWithBaseURL("file:///android_asset/myname.html", "数据显示", "text/html", "UTF-8", null);

	}
	class myinterface{
		private Context context;
		
		public myinterface(Context context) {
			this.context=context;
			// TODO Auto-generated constructor stub
		}
		
		
		public String getName(){
			
			return "pilisiya";
		}
		
		public void showToast(String toast)
        {
            // Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
			Log.e("TAG", "=====================");
            Toast.makeText(context,toast, Toast.LENGTH_LONG).show();
            Log.e("TAG", "*********************");
        }
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
			webView.goBack();
			return true;

		}
		return super.onKeyDown(keyCode, event);
	}

	@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;
	}

}


源码下载请点这里:
  • WebViewDemo.zip (1015.2 KB)
  • 下载次数: 17

你可能感兴趣的:(html,android,javascript,java)