63 votes

Fragment re-créé sur fond de navigation afficher l'élément sélectionné

Voici mon code pour le fond de navigation afficher l'élément sélectionné

bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {  
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    Fragment fragment = null;
    switch (item.getItemId()) {
        case R.id.action_one:
            // Switch to page one
            fragment = FragmentA.newInstance();
            break;
        case R.id.action_two:
            // Switch to page two
            fragment = FragmentB.newInstance();
            break;
        case R.id.action_three:
            // Switch to page three
            fragment = FragmentC.newInstance();
            break;
    }
    getSupportFragmentManager().beginTransaction().replace(R.id.container,fragment,"TAG").commit();
    return true;
}
});

Maintenant, mon problème est qu'à chaque fois le fragment est re-créé et ne veulent pas de fragment à être recréés à chaque fois j'ai aussi essayé d'ajouter addToBackStack(null) mais ce cas sur le bouton de retour de la presse ne cesse d'apparaître des fragments de la pile, ce qui je ne veux pas.

Est-il possible d'afficher des fragments sur le fond de la barre de navigation sélectionné, sans créer à nouveau fragment

26voto

Viven Points 412

Avec le soutien de la bibliothèque v26 vous pouvez le faire

FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();

Fragment curFrag = mFragmentManager.getPrimaryNavigationFragment();
if (curFrag != null) {
    fragmentTransaction.detach(curFrag);
}

Fragment fragment = mFragmentManager.findFragmentByTag(tag);
if (fragment == null) {
    fragment = new YourFragment();
    fragmentTransaction.add(container.getId(), fragment, tag);
} else {
    fragmentTransaction.attach(fragment);
}

fragmentTransaction.setPrimaryNavigationFragment(fragment);
fragmentTransaction.setReorderingAllowed(true);
fragmentTransaction.commitNowAllowingStateLoss();

16voto

Mazen Jameel Points 41

J'ai connu le même problème et j'ai enfin j'ai trouvé la solution, vous pouvez essayer ce code. c'est un travail pour moi.

import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.FrameLayout;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
public BottomNavigationView bv;
public home_fragment home;
public account_fragment afrag;
public other_fragment other;
public FrameLayout fr;
android.support.v4.app.Fragment current;
//public FragmentTransaction frt;
    public static int temp=0;
    final Fragment fragment11 = new account_fragment();
    final Fragment fragment22 = new home_fragment();
    final Fragment fragment33 = new other_fragment();
    final FragmentManager fm = getSupportFragmentManager();
    Fragment active = fragment11;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bv=(BottomNavigationView) findViewById(R.id.navigationView);


        fm.beginTransaction().add(R.id.main_frame, fragment33, "3").hide(fragment33).commit();
        fm.beginTransaction().add(R.id.main_frame, fragment22, "2").hide(fragment22).commit();
        fm.beginTransaction().add(R.id.main_frame,fragment11, "1").commit();
bv.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {

            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.account:
                        fm.beginTransaction().hide(active).show(fragment11).commit();
                        active = fragment11;
                        return true;

                    case R.id.home1:
                        fm.beginTransaction().hide(active).show(fragment22).commit();
                        active = fragment22;
                        return true;

                    case R.id.other:
                        fm.beginTransaction().hide(active).show(fragment33).commit();
                        active = fragment33;
                        return true;
                }
                return false;
            }
        });
      bv.setOnNavigationItemReselectedListener(new BottomNavigationView.OnNavigationItemReselectedListener() {
          @Override
          public void onNavigationItemReselected(@NonNull MenuItem item) {
              Toast.makeText(MainActivity.this, "Reselected", Toast.LENGTH_SHORT).show();

          }
      });


    }

}

8voto

Maxwell Points 967

Être prudent lors de l'utilisation d' replace. Même si la transmission d'un fragment qui existe déjà dans la mémoire, replace va redémarrer le fragment du cycle de vie. Pour éviter un redémarrage, l'objet de la transaction méthodes inclut add, show, et hide, qui peut être utilisé pour montrer le bon fragment sans redémarrer il.

private fun switchFragment(index: Int) {
    val transaction = supportFragmentManager.beginTransaction()
    val tag = fragments[index].tag

    // if the fragment has not yet been added to the container, add it first
    if (supportFragmentManager.findFragmentByTag(tag) == null) {
        transaction.add(R.id.container, fragments[index], tag)
    }

    transaction.hide(fragments[navigationBar.currentTabPosition])
    transaction.show(fragments[index])
    transaction.commit()
}

7voto

Essayez ceci :

bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    Fragment fragment = null;
                    Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.container);
                    switch (item.getItemId()) {
                        case R.id.action_one:
                            // Switch to page one
                            if (!(currentFragment instanceof FragmentA)) {
                                fragment = FragmentA.newInstance();
                            }
                            break;
                        case R.id.action_two:
                            // Switch to page two
                            if (!(currentFragment instanceof FragmentB)) {
                                fragment = FragmentB.newInstance();
                            }
                            break;
                        case R.id.action_three:
                            // Switch to page three
                            if (!(currentFragment instanceof FragmentC)) {
                                fragment = FragmentC.newInstance();
                            }
                            break;
                    }
                    getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment, "TAG").commit();
                    return true;
                }
            });

Qui obtiendra le courant fragment dans votre container et si vous cliquez de nouveau sur ce fragment qui ne sera pas ré ajouter le fragment.

4voto

Pb Studies Points 542

Utilisation setOnNavigationItemReselectedListener comme ceci:

private BottomNavigationView.OnNavigationItemReselectedListener onNavigationItemReselectedListener
            = new BottomNavigationView.OnNavigationItemReselectedListener() {

        @Override
        public void onNavigationItemReselected(@NonNull MenuItem item) {
            Toast.makeText(MainActivity.this, "Reselected", Toast.LENGTH_SHORT).show();
        }
    };

et d'appeler à l'aide:

navigation.setOnNavigationItemReselectedListener(onNavigationItemReselectedListener);

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X