如何为导航和当前活动设置On back选项

问题描述 投票:0回答:2

当我从主页单击后退按钮时,我创建了一个具有列表视图的应用程序,它将举起一条消息,并要求退出或不退出。在实现导航抽屉并设置打开和关闭之后。但是当我从导航中单击“后退”按钮时,返回并弹出我设置为页的吐司。

@Override
public void onBackPressed() {

    if (drawerLayout.isDrawerOpen(GravityCompat.START)){
        drawerLayout.closeDrawer(GravityCompat.START);
    }else{
        super.onBackPressed();
    }

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Are you sure you want to Exit?")
            .setCancelable(false)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                    AdminHome.super.onBackPressed();
                }
            })

            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

    AlertDialog alertDialog = builder.create();
    alertDialog.show();
}

当我从导航栏中单击并从主页设置吐司时,如何停止吐司消息。

java android android-layout button navigation
2个回答
0
投票

将AlertDialog代码放在else块中。


0
投票

嗨,您可以这样更改代码

@Override
public void onBackPressed() {

if (drawerLayout.isDrawerOpen(GravityCompat.START)){
    drawerLayout.closeDrawer(GravityCompat.START);
}else{
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to Exit?")
        .setCancelable(false)
        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
                AdminHome.super.onBackPressed();
            }
        })

        .setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

AlertDialog alertDialog = builder.create();
alertDialog.show();
}

}

© www.soinside.com 2019 - 2024. All rights reserved.