[需要帮助。如何在工具栏中使用警报对话框执行注销?因为我希望在用户想要注销到他的帐户时显示警告对话框。我正处于学习的阶段。希望你能帮我们嘿嘿。这是我的注销活动的代码::] [1] [2]
[1]: https://i.stack.imgur.com/lU7i1.png
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setMessage("Are you sure?")
.setPositiveButton("Logout", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
}).setNegativeButton("Cancel", null);
AlertDialog alert1 = alert.create();
alert1.show();
if (id == R.id.action_settings) {
logout();
return true;
}
return super.onOptionsItemSelected(item);
}
private void logout() {
startActivity(new Intent(this, LoginActivity.class));
finish();
}
答案 0 :(得分:0)
你需要考虑算法结构。
首先,用户单击选项菜单并选择注销。
然后,显示弹出窗口。
最后,用户与此弹出窗口进行交互并验证注销。
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
// This is first step.
showPopup();
return true;
}
return super.onOptionsItemSelected(item);
}
// first step helper function
private void showPopup() {
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setMessage("Are you sure?")
.setPositiveButton("Logout", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
logout(); // Last step. Logout function
}
}).setNegativeButton("Cancel", null);
AlertDialog alert1 = alert.create();
alert1.show();
}
private void logout() {
startActivity(new Intent(this, LoginActivity.class));
finish();
}