在片段中具有警告对话框的背面按压方法是可能的

时间:2016-01-29 07:42:23

标签: java android

@Override
    public void onBackPressed() {


            Log.d("back button", "back button pressed");
            AlertDialog.Builder ad1=new AlertDialog.Builder(getActivity());
            ad1.setMessage("Are you sure you want to exit? ");
            ad1.setCancelable(false);

            ad1.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                    Intent i = new Intent(getActivity(), LoginActivity.class);
                    startActivity(i);

                }
            });


            ad1.setNegativeButton("NO", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface arg0, int arg1) {

                    Intent i = new Intent(getActivity(), FrndsearchFragment.class);
                    startActivity(i);

                }
            });


            AlertDialog alert=ad1.create();
            alert.show();

        }

使用我在@Override得到错误的代码,我写了 super.onBackPressed ,我在 super.onBackPressed 中得到onBackPressed。

1 个答案:

答案 0 :(得分:0)

是的,您可以通过覆盖onKeyDown方法来执行相同操作。

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if(keyCode == KeyEvent.KEYCODE_BACK) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(false);
        builder.setTitle("Exit");
        builder.setMessage("Do you want to exit the application?");
        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                exit();
            }
        });
        builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

private void exit() {
    finish();
}