I've added custom keyboard to my Fragment and now I want to implement closing keyboard when on back pressed.
class CustomKeyboard
{
public void init(Context context) {
//...
FragmentManager fragmentManager = ((Activity) context).getFragmentManager();
boolean fragmentPopped = fragmentManager.popBackStackImmediate(TAG, 0);
if (!fragmentPopped) {
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.addToBackStack(TAG);
fragmentTransaction.commit();
}
}
}
The problem is init
calls every time when screen rotated because I create CustomKeyboard in public void onActivityCreated(final Bundle savedInstanceState)
fragmentPopped=false
every time, so CustomKeyboard may be added to BackStack more than one time.
My question:
Is it possible to add BackStackEntry to BackStack if not exists without using
getBackStackEntryCount()
method?
Try the below updated code.
public void init(Context context) {
FragmentManager fragmentManager = ((Activity) context).getFragmentManager();
boolean fragmentPopped = fragmentManager.popBackStack(TAG, 0);
if (!fragmentPopped) {
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.addToBackStack(TAG);
fragmentTransaction.commit();
}
}
You can do something like this :
FragmentManager fm= getSupportFragmentManager();
if(fm!=null && getSupportFragmentManager().getFragments()!=null) {
boolean fragmentPopped = fm.popBackStackImmediate(TAG, 0);
if (!fragmentPopped && getSupportFragmentManager().getFragments().size() == 0) {
FragmentTransaction ft = fm.beginTransaction();
ft.addToBackStack(TAG);
ft.commit();
}
}
Also You can clean your Backstack first like this and then replace your fragment :
private void cleanBackStack() {
FragmentManager fm = getSupportFragmentManager();
if (fm != null && fm.getFragments() != null) {
if (fm.getFragments().size() > 1) {
for (int entry = 0; entry < fm.getFragments().size(); entry++) {
fm.popBackStackImmediate();
}
} else if (fm.getFragments().size()==1){
fm.popBackStack();
}else if(fm.getFragments().size()==0){
//REPLACE YOUR FRAGMENT
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With