2012-02-23 65 views
3

我們可以改寫硬件後退按鈕功能嗎?我有點困惑,這對我有幫助。改寫Android硬件後退按鈕功能

+0

請檢查這個http://stackoverflow.com/questions/3614849/intercepting-the-back-button – 2012-02-23 09:36:36

+0

有很多重複的問題 – 2012-02-23 09:36:43

+0

由於方式已在別人的答案中提供,我只想說一個事情:注意官方文檔:「不要接管Back按鈕,除非你絕對需要」https://developer.android.com/guide/practices/ui_guidelines/activity_task_design.html,因爲它打破了用戶體驗整個系統。 – coolcfan 2012-02-23 09:41:58

回答

6
@Override public void onBackPressed(){ 
    //do your stuff here 
} 

如果涉及到特定的鍵東西,那麼你可以去這樣的:

@Override 
public boolean onKeyDown(int keyCode, KeyEvent event) { 
    if (keyCode == KeyEvent.Any_Key_Code) { 
     //your stuff here 
     return true; 
    } 
    return super.onKeyDown(keyCode, event); 
} 
2

看到這個

public boolean onKeyDown(int keyCode, KeyEvent event) { 
    if (keyCode == KeyEvent.KEYCODE_BACK) { 

     Toast.makeText(getApplicationContext(), "back button pressed", 
       Toast.LENGTH_SHORT).show(); 
     return true; 
    } 

    return super.onKeyDown(keyCode, event); 
} 
2
@Override 
public boolean onKeyDown(int keyCode, KeyEvent event) { 
    if (keyCode == KeyEvent.KEYCODE_BACK) { 
     // do your stuff here 
     return true; 
    } 
    return super.onKeyDown(keyCode, event); 
} 
8

您還可以覆蓋onBackPressed()

@Override 
public void onBackPressed(){ 
    //Your action 
} 
1
@Override 
public void onBackPressed() { 
    // Action to be performed 
    super.onBackPressed(); 
}