片段中的android onBackPressed方法需要帮助退出应用程序

时间:2014-04-22 05:02:20

标签: android fragment alert exit

在我的一个应用程序中,我正在使用片段。现在我想在后退键上添加退出警告框但是我无法在Fragment扩展类中获得public void onBackPressed()方法。我怎样才能做到这一点?我的MainActivity扩展了FragmentActivity。

public void onBackPressed() {   
    super.onBackPressed();
    alertbox("myappname", "Do You Want to Exit?");
}

但是它没有显示对话框,或者如果显示它会在1秒后消失。我做错了什么。

2 个答案:

答案 0 :(得分:0)

使用此功能退出

<强>码

 @Override
       public boolean onKeyDown(int keyCode, KeyEvent event) {
           if ((keyCode == KeyEvent.KEYCODE_BACK)) {
               AlertDialog.Builder alertbox = new AlertDialog.Builder(MainActivity.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
                       exit();
                   }
               });

               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);
       }
    public void exit()
    {
         Intent intent = new Intent(Intent.ACTION_MAIN);
         intent.addCategory(Intent.CATEGORY_HOME);
         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         startActivity(intent);
    }

答案 1 :(得分:0)

这个函数的作用相同....就像在反向表达....把它放在包含片段的活动中,如果你有多个片段,那么检查你想要显示出口的片段警报箱........

@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        // Handle the back button
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            // Ask the user if they want to quit
            if (yourfragment.isVisible()) {
                new AlertDialog.Builder(this)

                        .setIcon(android.R.drawable.ic_dialog_alert)

                        .setTitle("Exit")

                        .setMessage("Are you sure you want to leave?")

                        .setNegativeButton(android.R.string.cancel, null)

                        .setPositiveButton(android.R.string.ok,
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog,
                                            int which) {

                                        // Exit the activity

                                        finish();

                                    }

                                })

                        .show();

                // Say that we've consumed the event
                return true;

            }

        }

        return super.onKeyDown(keyCode, event);

    }