首页 > 代码库 > WebView的返回功能

WebView的返回功能

WebView 实现返回到最后一个 在退出

 

 

import android.app.Activity;import android.os.Bundle;import android.view.KeyEvent;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.webkit.WebChromeClient;import android.webkit.WebView;import android.webkit.WebViewClient;/** * Created by Administrator on 2015/1/4. */public class WebViewTest extends Activity implements View.OnKeyListener {    private WebView webView;    private String url = "http://www.baidu.com/";    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.webview);        webView = (WebView) findViewById(R.id.webView);        webView.setWebChromeClient(new chromeClient());        webView.setWebViewClient(new webViewClient());        webView.getSettings().setJavaScriptEnabled(true);        webView.getSettings().setAllowFileAccess(true);        webView.getSettings().setPluginsEnabled(true);        webView.getSettings().setAllowFileAccess(true);        webView.setOnKeyListener(this);        webView.loadUrl(url);    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        getMenuInflater().inflate(R.menu.activity_weview, menu);        return super.onCreateOptionsMenu(menu);    }    @Override    public boolean onOptionsItemSelected(MenuItem item) {        switch (item.getItemId()) {            case R.id.menu_settings:                finish();                System.exit(0);                break;        }        return super.onOptionsItemSelected(item);    }    @Override    public boolean onKey(View v, int keyCode, KeyEvent event) {        if (event.getAction() == KeyEvent.ACTION_DOWN) {            if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {  //表示按返回键 时的操作                webView.goBack();   //后退                return true;    //已处理            }        }        return false;    }    class chromeClient extends WebChromeClient {        @Override        public void onProgressChanged(WebView view, int newProgress) {            if (newProgress == 100) {            }            super.onProgressChanged(view, newProgress);        }    }    class webViewClient extends WebViewClient {        //重写shouldOverrideUrlLoading方法,使点击链接后不使用其他的浏览器打开。        @Override        public boolean shouldOverrideUrlLoading(WebView view, String url) {            view.loadUrl(url);            //如果不需要其他对点击链接事件的处理返回true,否则返回false            return true;        }    }} 

 

WebView的返回功能