【发布时间】:2022-11-27 15:02:36
【问题描述】:
我目前正在开发一个 Android Studio 项目,我遇到了一个问题,无论我在菜单中选择哪个选项,它都会连续更改所有选项的活动,然后崩溃。 这是我的主页菜单功能:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
menu.removeItem(R.id.HomePage);
if (sp.getLong("User_Id", -1) != -1) {
menu.removeItem(R.id.Login);
menu.removeItem(R.id.SignUp);
}
else {
menu.removeItem(R.id.LogOut);
}
if (sp.contains("User_Id")){
if (!database.userDao().GetUserById(sp.getLong("User_Id", -1)).getUserEmail().equals(R.string.admin_email))
menu.removeItem(R.id.UserList);
}
else
menu.removeItem(R.id.UserList);
return true;
}
@SuppressLint("NonConstantResourceId")
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.SignUp: {
startActivity(new Intent(MainActivity.this, RegisterActivity.class));
}
case R.id.Login: {
startActivity(new Intent(MainActivity.this, LoginActivity.class));
}
case R.id.UserList: {
startActivity(new Intent(MainActivity.this, UserActivity.class));
}
case R.id.LogOut:{
builder.setMessage(R.string.logout_dialog_message).setTitle(R.string.logout_dialog_title).setCancelable(true).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
editor.clear();
editor.commit();
finish();
overridePendingTransition(0, 0);
startActivity(getIntent());
overridePendingTransition(0, 0);
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
case R.id.About: {
Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_about_dialog);
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.setCancelable(true);
dialog.getWindow().getAttributes().windowAnimations = R.style.animation;
ImageView image = dialog.findViewById(R.id.IVLogo);
TextView text = dialog.findViewById(R.id.TVText);
image.setBackground(getDrawable(R.drawable.logo));
text.setText("About us: We are regel2, the new best second hand app. In this app, you are able to buy and sell any product that you want, for any price that you want, all inside 1 app.");
dialog.show();
}
}
return super.onOptionsItemSelected(item);
}
注意:它甚至会打开已删除的菜单项(又名menu.removeItem(___)),当我单击关于项目时不会发生这种情况,这可能会有所不同,因为它是一个对话框。
【问题讨论】:
标签: java database android-studio sharedpreferences