如何操作后退按钮?

时间:2018-09-13 11:04:34

标签: android onbackpressed

当我按下“后退”按钮时,我希望它可以像意图进行某些特殊活动并刷新页面那样工作。我发现一些代码以这种方式工作,但是找不到正在执行我想要的代码的代码。预先感谢。

4 个答案:

答案 0 :(得分:0)

只需在您的活动中覆盖onBackPressed方法,例如:

@Override
public void onBackPressed() {
/** Write your code here that you want to execute on Backpress**/        
}

请勿在onBackPressed中使用super.onBackPressed(),因为它将被称为父活动onBackPressed方法并杀死当前活动。

答案 1 :(得分:0)

在活动中,您需要使用 onBackPressed()

@Override
public void onBackPressed() {

    //You'll put your code here, in my example below, i check if the user is sure

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Are you sure you want to cancel?")
            .setCancelable(false)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    YourActivity.this.finish();
                }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
    AlertDialog alert = builder.create();
    alert.show();
}

答案 2 :(得分:0)

答案 3 :(得分:0)

尝试以下代码。

@Override
    public void onBackPressed() {             
        Log.d(TAG, "onBackPressed: GoTo NextActivity");
        Intent intent = new Intent(getApplicationContext(),NextActivity.class); // Replace the NextActivity.class with the Activity you wish to open..
        startActivity(intent);
    }