2013-02-25 179 views
2

我在活动的布局中有一个webView。如果按后退按钮,我想这种观点也消失了,其他的观点变得可见,给我做了以下内容:android - 覆盖后退按钮

@Override 
public boolean onKeyDown(int keyCode, KeyEvent event) { 
    if (keyCode == KeyEvent.KEYCODE_BACK && web.getVisibility()==View.VISIBLE) { 
     restoreInitalState(); // set Visibility of Views 
     APP_CONSTANTS.LOGIN_OP_CANCELLED(getApplicationContext()); // inform the user that the current operation was cancelled 
    } 
    return super.onKeyDown(keyCode, event); 

} 

它的工作原理,但它调用我的方法后立即结束活动,就像如果后退按钮被按下2次。我需要保留当前的Activity,并且只需调用上面提到的方法。有什么建议么?

回答

3

您需要返回false。更改此:

if (keyCode == KeyEvent.KEYCODE_BACK && web.getVisibility()==View.VISIBLE) { 
    restoreInitalState(); // set Visibility of Views 
    APP_CONSTANTS.LOGIN_OP_CANCELLED(getApplicationContext()); // inform the user that the current operation was cancelled 
} 

这样:

if (keyCode == KeyEvent.KEYCODE_BACK && web.getVisibility()==View.VISIBLE) { 
    restoreInitalState(); // set Visibility of Views 
    APP_CONSTANTS.LOGIN_OP_CANCELLED(getApplicationContext()); // inform the user that the current operation was cancelled 
    return false; 
} 
+0

就是这样。谢谢 – Droidman 2013-02-25 17:55:17

1

我认为正确的方法是:

@Override 
public boolean onKeyDown(int keyCode, KeyEvent event) { 
    if (keyCode == KeyEvent.KEYCODE_BACK && web.getVisibility()==View.VISIBLE) { 
     restoreInitalState(); // set Visibility of Views 
     APP_CONSTANTS.LOGIN_OP_CANCELLED(getApplicationContext()); 
     return true; 
    } 
    return super.onKeyDown(keyCode, event); 
} 
1

或者只是使用的方法,onBackPressed()在YOUE Activity类,这是最简单的方法覆盖它。

1

我认为你正在寻找的回调方法是onBackPressed

但是,您当前的解决方案应该也能正常工作,您只需在if块内返回true,否则该事件将传播到另一个回调。