片段中的android后退按钮调用2次

时间:2014-04-22 06:13:59

标签: android fragment exit back-button

在我的一个应用程序中,我需要在后退键按下退出对话框,这是扩展片段,这是

View view = inflater.inflate(R.layout.fragment_layout1, null);
        view.setFocusableInTouchMode(true);
        view.requestFocus();
    view.setOnKeyListener(new OnKeyListener() {

        @Override
        public boolean onKey(View arg0, int keyCode, KeyEvent arg2) {
             Log.i("tag", "keyCode: " + keyCode);
                if( keyCode == KeyEvent.KEYCODE_BACK ) {
                        Log.i("tag", "onKey Back listener is working!!!");
                   // getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                    return true;
                } else {
                    return false;
                }
        }
    });

logcat的:

04-22 11:40:53.291: I/tag(31150): keyCode: 4
04-22 11:40:53.291: I/tag(31150): onKey Back listener is working!!!
04-22 11:40:53.351: I/tag(31150): keyCode: 4
04-22 11:40:53.351: I/tag(31150): onKey Back listener is working!!!

问题是这是2次......发生了什么

1 个答案:

答案 0 :(得分:0)

尝试使用代码

@Override
   public boolean onKeyDown(int keyCode, KeyEvent event) {
       if ((keyCode == KeyEvent.KEYCODE_BACK)) {
           AlertDialog.Builder alertbox = new AlertDialog.Builder(previousEntry.this);

           alertbox.setTitle("Do You Want To Exit ?");
           alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface arg0, int arg1) { 
                  // finish used for destroyed activity
                   finish();
               }
           });

           alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface arg0, int arg1) {
                       // Nothing will be happened when clicked on no button 
                       // of Dialog     
             }
           });

           alertbox.show();
       }
       return super.onKeyDown(keyCode, event);
   }