fragment监听onBackPressed返回键

可以不依赖activity进行fragment间的跳转和回退

在Fragment中重写onResume方法,实现OnKeyListener并监听按键:

@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;
        }
    });
}

你可能感兴趣的:(fragment,回退)