你好我有片段的活动。当我点击图标或类似的东西时,我可以打开一个片段 但我想用OnBackPressed方法关闭片段(或隐藏)。
我创造了这个:
private void onBackPressedInFragments(){
if(backgroundSelectFragment != null && backgroundSelectFragment.isVisible())
backgroundSelectFragment.getActivity().onBackPressed();
}
但是当我打开一个片段并点击Phone中的后退按钮时,我就关闭了应用程序。我的应用程序有一个活动和2个片段:
这里我创建并显示片段:
backgroundBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (backgroundSelectFragment == null) {
backgroundSelectFragment = new BackgroundSelectFragment();
FragmentManager fm = getFragmentManager();
fm.beginTransaction()
.add(R.id.main_relative, backgroundSelectFragment, "background")
.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out)
.show(backgroundSelectFragment)
.commit();
} else {
if (backgroundSelectFragment.isHidden()) {
showFragmentBackground();
} else {
hideFragmentBackground();
}
}
}
});
任何想法的人?
答案 0 :(得分:1)
在您的活动中覆盖onBackPressed
。如果背堆中有任何片段而不是popBackStack()
,则只需finish()
您的活动。
private boolean allowedToExit = false; // class level
@Override
public void onBackPressed() {
int backStackEntryCount = getSupportFragmentManager().getBackStackEntryCount();
// this is the last item
if (backStackEntryCount == 1) {
if (allowedToExit)
finish();
else {
allowedToExit = true;
Toast.makeText(this, "Press again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
allowedToExit = false;
}
}, 1000);
return;
}
}
// we have more than 1 fragments in back stack
if (backStackEntryCount > 1) {
getSupportFragmentManager().popBackStackImmediate();
// getSupportFragmentManager().beginTransaction().commit();
} else
super.onBackPressed();
}