【发布时间】:2017-12-29 10:51:32
【问题描述】:
这里发生的情况是,一旦按下后退按钮,活动就会重新加载,再次按下后退按钮会退出应用程序。我希望它是一次,即第一次
我尝试了很多方法,比如尝试 onBackPressed 方法,但没有一个奏效。我想解决这个问题,当用户按下后退按钮时,他应该退出应用程序。 同样的情况也发生在其他活动中,其中我有一个登录页面,一旦用户进入登录页面,如果他希望退出应用程序并按下后退按钮,那么在我的情况下,登录页面会再次重新加载,然后再次按下返回按钮会退出应用程序。
下面是代码。
public class MainActivity extends AppCompatActivity {
CardView attendance, time_table, directory, daily_work, notices, transport,remarks,calendar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences preferences = getSharedPreferences("user_login",MODE_PRIVATE);
boolean isLogin = preferences.getBoolean("isLogin", false);
if(isLogin)
{
init();
methodListener();
}
else {
Intent intent = new Intent(this, Login.class);
startActivity(intent);
finish();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.logout) {
SharedPreferences preferences = getSharedPreferences("user_login", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();
Intent intent = new Intent(this,Login.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
finish();
}
return super.onOptionsItemSelected(item);
}
}
请提出一些解决方法。
【问题讨论】:
-
你用 onBackPressed() 方法尝试了什么?这是正确的方法。
-
你试过在onBackPressed方法中添加finish()吗?
-
显示“init”和“methodLIstener”方法——你的错误可能就在那里。
标签: android onbackpressed