Bottom bar fragment reload

giorgio rota picture giorgio rota · Jun 29, 2017 · Viewed 7.5k times · Source

These are my main activity and my fragment. I don't want to reload the fragment every time that I return on that tab of bottombar view. Infact now every time I click on that tab the image reloads. Any solutions?

Main Activity

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    BottomNavigationView bottomNavigationView = (BottomNavigationView)
            findViewById(R.id.navigation);

    bottomNavigationView.setOnNavigationItemSelectedListener
            (new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    Fragment selectedFragment = null;

                    switch (item.getItemId()) {
                        case R.id.action_item1:

                                selectedFragment = Tab1.newInstance();

                            break;
                        case R.id.action_item2:
                            selectedFragment = Tab2.newInstance();
                            break;
                        case R.id.action_item3:
                            selectedFragment = Tab3.newInstance();
                            break;
                    }
                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                    transaction.replace(R.id.frame_layout, selectedFragment);
                    transaction.commit();
                    return true;
                }
            });

    //Manually displaying the first fragment - one time only
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.frame_layout, Tab1.newInstance());
    transaction.commit();

    //Used to select an item programmatically
    //bottomNavigationView.getMenu().getItem(2).setChecked(true);
}
}

Fragment

public class Tab1 extends Fragment {
ImageView imageview;
ProgressDialog progressDialog;
public static Tab1 newInstance() {
    Tab1 fragment = new Tab1();
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView =  inflater.inflate(R.layout.activity_tab1, container, false);

    imageview =(ImageView)  rootView.findViewById(R.id.immagine);
    FirebaseStorage storage = FirebaseStorage.getInstance();
    StorageReference storageRef = storage.getReferenceFromUrl("gs://test-x3b2c.appspot.com").child("lc.jpg");

    //download file as a byte array

    progressDialog = ProgressDialog.show(getActivity(), "Attendi",
            "Sto caricando il luogo comune", true);
    try {
        final File localFile = File.createTempFile("images", "jpg");
        storageRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
                Bitmap bitmap = BitmapFactory.decodeFile(localFile.getAbsolutePath());
                imageview.setImageBitmap(bitmap);
                progressDialog.dismiss();

            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
            }
        });
    }
    catch (IOException e) {
    }
    return rootView;
}
}

Answer

Ayush Khare picture Ayush Khare · Jun 29, 2017

Modify your code like this:

    switch (item.getItemId()) {
                    case R.id.action_item1:
                        selectedFragment = Tab1.newInstance();
                        break;
                    case R.id.action_item2:
                        selectedFragment = Tab2.newInstance();
                        break;
                    case R.id.action_item3:
                        selectedFragment = Tab3.newInstance();
                        break;
                }

                if(selectedFragment ! =null) {
                 FragmentTransaction transaction = 
                      getSupportFragmentManager().beginTransaction();
                 transaction.replace(R.id.frame_layout, selectedFragment, selectedFragment.getTag());
                 transaction.commit();
                }

                return true;

    }

The Fragment tag avoids recreating a fragment again if it already exists.