开发者

Android keycode_back closes application

开发者 https://www.devze.com 2023-04-01 21:51 出处:网络
I want the back button 开发者_C百科on the android phone to act like the back button for my web browser. At present, it closes the application instead of going back to the previous screen.

I want the back button 开发者_C百科on the android phone to act like the back button for my web browser. At present, it closes the application instead of going back to the previous screen.

I wrote this incredibly ugly hack to get around it as follows:

Stack stack=new Stack();

and every time a new webview is loaded i store it in the stack using

stack.push(url);

@Override     
         public boolean onKeyDown(int keyCode, KeyEvent event) {          
             // Back?         
             if (keyCode == KeyEvent.KEYCODE_BACK) {             
                     // Back             
                     String url = stack.pop();               
                     if(url.indexOf("index.html")>0)stack.push("file:///android_asset/index.html");
                     this.loadUrl(url);
                 }          
             // Return         
             return true;   
             }

Now, I really want to do it the android way but have no clue how to achieve this...

Any help would be most appreciated.

@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event)  {    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {        // do something on back.        return true;    }    return super.onKeyDown(keyCode, event);}

with

@Overridepublic void onBackPressed() {// do something on back.return;}

does not work for me and I dont konw why (sad android face)


You can do it like this:

private WebView webView;

...

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

...

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && webView != null && webView.canGoBack()) {
        webView.goBack();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号