I have a MainActivity
, that is supposed to switch between two fragments: Content and Settings (extends PreferenceFragmentCompat
). Everything worked fine, but recently I implemented Dagger 2 dependency injection, and my Settings fragment started to blink. When you press settings item on the bottom navigation bar, sometimes settings fragment appears, then disappears for few milliseconds and appears again.
I don't see any explainable reason why this happens, and what exactly happens.
Can you, please, explain what's happening and how to fix this?
Here is the code of my MainActivity.
MainActivity.java
public class MainActivity extends BaseActivity
implements BottomBarConstructor.BottomBarSelectItemListener,
MainActivityContract.View {
public final static int REQUEST_CODE = 1;
@Inject
MainActivityContract.Presenter<MainActivityContract.View> presenter;
private EffectsControlFragment effectsControlFragment;
private SettingsFragment settingsFragment;
private FragmentManager fragmentManager;
private BottomNavigationView bottomNavigationView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createFragments();
bindViews();
initializeFragment();
getActivityComponent().inject(this);
presenter.onAttach(this);
presenter.onBottomBarCreate();
}
@Override
public void onSelectItem(String fragmentId) {
changeFragment(fragmentId);
}
@Override
public void createBottomBar(List<BottomBarItem> items) {
new BottomBarConstructor(this, bottomNavigationView).create(items);
}
public void changeFragment(String fragmentId) {
switch (fragmentId) {
case "main":
replaceFragment(effectsControlFragment, fragmentId);
break;
case "settings":
replaceFragment(settingsFragment, fragmentId);
break;
default:
replaceFragment(EffectsControlFragment.newInstance(), fragmentId);
}
}
private void replaceFragment(Fragment fragment, String fragmentId) {
fragmentManager.beginTransaction()
.replace(R.id.fragment_container, fragment, fragmentId)
.commit();
}
private void createFragments() {
effectsControlFragment = EffectsControlFragment.newInstance();
settingsFragment = SettingsFragment.newInstance();
fragmentManager = getSupportFragmentManager();
}
private void bindViews() {
bottomNavigationView = findViewById(R.id.navigation_bar);
}
private void initializeFragment() {
fragmentManager.beginTransaction()
.add(R.id.fragment_container, EffectsControlFragment.newInstance())
.commit();
}
}
Adding .addToBackStack(null)
to the fragmentTransaction solved my problem.
private void replaceFragment(Fragment fragment, String fragmentId) {
fragmentManager.beginTransaction()
.replace(R.id.fragment_container, fragment, fragmentId)
.addToBackStack(null)
.commit();
}