[英]How can i get the android back button to close the app everytime the home button is clicked?
Hi I am new to android development. 嗨,我是android开发的新手。 I am facing a problem with fragments. 我遇到了碎片问题。 Initially, anytime i opened a fragment and hit the back button on the android device, it closes the app until i found a solution which involved the use of fragmentTransaction.addToBackStack(null) method; 最初,每当我打开一个片段并按下android设备上的后退按钮时,它将关闭该应用程序,直到我找到一个涉及使用fragmentTransaction.addToBackStack(null)方法的解决方案为止; but my problem is that if i open other fragments from the home fragment and click the home button each time i opened a new fragment, the back button, keeps going back to the previous fragment even after it gets to the home fragment. 但是我的问题是,如果我每次打开一个新片段时都从home片段中打开其他片段,然后单击home按钮,则后退按钮即使回到home片段后也会一直返回到先前的片段。 To explain further lets assume this are my events on the app. 为了进一步说明,假设这是我在应用程序上的事件。
app opens => Home fragment => fragment B => Home fragment => fragment c => fragment D =>Home fragment 应用程序打开=>主页片段=>片段B =>主页片段=>片段c =>片段D =>主页片段
when i hit the back button this is what it does: 当我按下后退按钮时,它的作用是:
Home fragment => fragment D => fragment c => Home fragment => fragment B => Home fragment => app closes 主页片段=>片段D =>片段c =>主页片段=>片段B =>主页片段=>应用关闭
I don't like the fact that even after hitting the home fragment, the app continues going back to the fragments before the home fragment. 我不喜欢这样的事实,即使在击中主片段后,该应用程序仍会继续返回到主片段之前的片段。
Please how can i make sure that every time the user gets to the home fragment and presses the back button it cancels all other fragments before it and just closes the app. 请我如何确保每次用户到达首页片段并按返回按钮时,它都会取消所有其他片段,然后关闭应用程序。
I hope i explained this well. 我希望我能解释得很好。 please any help would be very helpful. 请任何帮助将非常有帮助。 Thank you. 谢谢。
Always beware of coding an app that bucks the Android Framework... 始终提防编写与Android框架背道而驰的应用程序的代码...
Clear Fragment stack: 清除片段堆栈:
getSupportFragmentManager().popBackStack(null,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
Clear Activity stack: 清除活动堆栈:
Intent intent = new Intent(Your_Current_Activity.this,
Your_Destination_Activity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK
|Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
You can try with these two methods in your activity - 您可以在活动中尝试使用这两种方法-
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == android.R.id.home){
finish();
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
finish();
super.onBackPressed();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.