原文地址:
http://stackoverflow.com/questions/22552958/handling-back-press-when-using-fragments-in-android
簡(jiǎn)單好用,一目了然。
Fragment中重寫OnResume方法接校,添加如下代碼痘儡。
@Override
public void onResume() {
super.onResume();
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){
// handle back button
return true;
}
return false;
}
});
}