2

I just started learning Android Studio. I want to know how to make a fragment not blinking when we click the menu bottom navbar repeatedly. I use the default bottom navigation activity.

I use default bottom navigation activity

And this is the first code in the main activity

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    BottomNavigationView navView = findViewById(R.id.nav_view);
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
            R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
            .build();
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
    NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
    NavigationUI.setupWithNavController(navView, navController);
    }
}

And this is one of the fragment code

public class HomeFragment extends Fragment {

private HomeViewModel homeViewModel;

public View onCreateView(@NonNull LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {
    homeViewModel =
            ViewModelProviders.of(this).get(HomeViewModel.class);
    View root = inflater.inflate(R.layout.fragment_home, container, false);
    final TextView textView = root.findViewById(R.id.text_home);
    homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
        @Override
        public void onChanged(@Nullable String s) {
            textView.setText(s);
        }
    });
    return root;
    }
}

And this the HomeViewModel code

public class HomeViewModel extends ViewModel {

private MutableLiveData<String> mText;

public HomeViewModel() {
    mText = new MutableLiveData<>();
    mText.setValue("This is home fragment");
}

public LiveData<String> getText() {
    return mText;
}
}

I run the app and when I click repeatedly the bottom bar, the fragment blink. (The text of "This is home fragment" blink)

When I click repeatedly, the fragment blinks

Please, do you know how to make a fragment not blink or not reload?

Imam Faried
  • 43
  • 1
  • 8

1 Answers1

1

A quick idea. Keep track of which navigation fragment is selected. And if a navigation fragment is selected lets say home fragment then if user reselect the home navigation then just ignore the click event. This way if the home button is already selected then the click event on the home navigation wouldn't do anything, it will only load the navigation home the first time. This should solve your problem. Happy coding!

Md Golam Rahman Tushar
  • 2,175
  • 1
  • 14
  • 29