其他分享
首页 > 其他分享> > Android开发 Fragment里监听返回键

Android开发 Fragment里监听返回键

作者:互联网

@Override
public void onResume() {
    super.onResume();
    getView().setFocusableInTouchMode(true);
    getView().requestFocus();
    getView().setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View view, int i, KeyEvent keyEvent) {
            if(keyEvent.getAction() == KeyEvent.ACTION_DOWN && i == KeyEvent.KEYCODE_BACK){
                Toast.makeText(getActivity(), "按了返回键", Toast.LENGTH_SHORT).show();
                return true;
            }
            return false;
        }
    });
}

  kotlin

override fun onResume() {
        super.onResume()

        requireView().isFocusableInTouchMode = true
        requireView().requestFocus()
        requireView().setOnKeyListener(View.OnKeyListener { view, i, keyEvent ->
            if (keyEvent.action === KeyEvent.ACTION_DOWN && i == KeyEvent.KEYCODE_BACK) {
                showHintLogOutDialog()
                //Toast.makeText(activity, "按了返回键", Toast.LENGTH_SHORT).show()
                return@OnKeyListener true
            }
            false
        })
    }

  

标签:Toast,getView,onResume,KeyEvent,Fragment,keyEvent,Android,true,监听
来源: https://www.cnblogs.com/changyiqiang/p/15775419.html