将网页嵌入到android应用中

将网页嵌入到android应用中

 

package com.android.webviewtest;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;


public class MainActivity extends Activity {
	private WebView myWebView ;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		//获取webview控件
		myWebView = (WebView) findViewById(R.id.webview);
		//加载服务器上的页面
		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) {
	    // Check if the key event was the Back button and if there's history
	    if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
	        myWebView.goBack();
	        return true;
	    }
	  //  return true;
	    // If it wasn't the Back key or there's no web page history, bubble up to the default
	    // system behavior (probably exit the activity)
	    return super.onKeyDown(keyCode, event);
	}


	
}

package com.android.webviewtest;

import android.content.Context;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

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


 


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值