Issue
How to prevent opening a fragment from navigation drawer if that fragment is already opened, when the fragment is opened and click in the NavigationDrawer item the fragment reCreates again, So how to check if the fragment is already opened?
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (id == R.id.fragmentA) {
{ FragmentA fragment = new FragmentA();
transaction.add(R.id.main_screen, fragment1, "MainFrag").addToBackStack(null);
}
} else if (id == R.id.fragmentB) {
FragmentB fragment = new FragmentB();
transaction.add(R.id.main_screen, fragment).addToBackStack(null);
} else if (id == R.id.fragmentC) {
FragmentC fragment = new FragmentC();
transaction.replace(R.id.main_screen, fragment).addToBackStack(null);
}
Solution
I solved it in this way:
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
Fragment f = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if (id == R.id.n_1 && !(f instanceof MainFragment)) {
MainFragment fragment = new MainFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
} }
Answered By - Eliran Tutia
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.