Home > Enterprise >  (Android) NavigationBarView clear GridView
(Android) NavigationBarView clear GridView

Time:11-09

I have three fragment in NavigationBarView.

First fragment has gridview(gridview data is dynamic by network search).

But when I go to second fragment and back to first fragment, the gridview in first fragment is clear.

How can I prevent the gridview's data from being cleared?

Here my navigation code.

// in global variable
NavigationBarView navigationBarView;
FirstFragment firstFragment;
SecondFragment secondFragment;
ThirdFragment thirdFragment;

// ...

firstFragment = new FirstFragment();
secondFragment= new SecondFragment();
thirdFragment = new ThirdFragment();

getSupportFragmentManager().beginTransaction().replace(R.id.containers, firstFragment).commit();

navigationBarView = findViewById(R.id.bottom_navigationview);
navigationBarView.setKeepScreenOn(true);
navigationBarView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {

        switch(item.getItemId())
        {
            case R.id.menu_first:
                getSupportFragmentManager().beginTransaction().replace(R.id.containers, firstFragment).commit();
                return true;
            case R.id.menu_second:
                getSupportFragmentManager().beginTransaction().replace(R.id.containers, secondFragment).commit();
                return true;
            case R.id.menu_third:
                getSupportFragmentManager().beginTransaction().replace(R.id.containers, thirdFragment).commit();
                return true;
        }
        return false;
    }
});

CodePudding user response:

addToBackStack method when replacing one fragment by another:

getFragmentManager().beginTransaction().replace(R.id.content_frame, fragment).addToBackStack("my_fragment").commit();

and also use onbackpressed to back with state using back button

@Override
public void onBackPressed() {
    if (getParentFragmentManager().getBackStackEntryCount() > 0) {
        getParentFragmentManager().popBackStack();
    } else {
        super.onBackPressed();
    }
}

use same popBackStack() to navigate from navigationbar also

  • Related