返回按钮关闭WebView应用程序

时间:2011-07-07 15:39:42

标签: android android-webview

我有一个如下的应用程序,作为FullScreen.NoTitleBar运行:

public class BrowserActivity extends Activity {
private String lastUrl = "http://www.google.com";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    WebView web = (WebView) findViewById(R.id.webview);

    WebSettings settings = web.getSettings();
    settings.setJavaScriptEnabled(true);
    settings.setJavaScriptCanOpenWindowsAutomatically(false);
    settings.setSupportMultipleWindows(false);
    settings.setSupportZoom(false);
    settings.setPluginsEnabled(true);

    web.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            lastUrl = url;
            view.loadUrl(url);
            return true;
        }
    });
    web.setVerticalScrollBarEnabled(false);
    web.setHorizontalScrollBarEnabled(false);

    web.loadUrl(lastUrl);
}
}

“lastUrl”用于处理方向更改,并让用户在导航时所在的页面上。

但我的问题是,如果用户按照某些链接然后点击返回按钮,应用程序就会关闭而不是返回页面。我怎么处理呢?

1 个答案:

答案 0 :(得分:2)

我通过处理返回并跟踪用户访问的URL来解决它。

public class BrowserActivity extends Activity {
    private Stack<String> urls = new Stack<String>();;

    private String lastUrl = "http://www.google.com/";
    private WebView web;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);
        try {
        web = (WebView) findViewById(R.id.webview);

        WebSettings settings = web.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(false);
        settings.setSupportMultipleWindows(false);
        settings.setSupportZoom(false);
        settings.setPluginsEnabled(true);

        web.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                urls.push(lastUrl);
                lastUrl = url;
                return false;
            }
        });
        web.setVerticalScrollBarEnabled(false);
        web.setHorizontalScrollBarEnabled(false);

        web.loadUrl(lastUrl);
    }

    public boolean onKeyDown(int keyCode, KeyEvent evt) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (urls.size() > 0) {
                lastUrl = urls.pop();
                web.loadUrl(lastUrl);
            } else
                finish();
            return true;
        }

        return false;
    }
}