如何实施再次按下以退出android studio中的Pls。请参阅此处的我的编码。我检查了所有与此有关的讨论,但没有使用我的代码。我必须确保在按下后背时,始终在关闭前先回家。 提前非常感谢您!
/**
* On back pressed, always go to home fragment before closing
*/
@Override
public void onBackPressed() {
//if stack has items left
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
//get current fragment
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.mainFragment);
//only close if in CategoryFragment else go to CategoryFragment
if (fragment instanceof SearchFragment) {
finish();
} else {
changeFragment(new SearchFragment());
}
} else {
super.onBackPressed();
}
}
答案 0 :(得分:0)
OnBackPress
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish()
答案 1 :(得分:0)
如果您想再次使onBackPressed退出活动,则可以使用此功能
public void onBackPressed() {
count++;
if (count > 1) {
moveTaskToBack(true);
} else {
showToast("Press back again to Leave!");
// resetting the counter in 2s
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
count = 0;
}
}, 2000);
}
}