Search code examples
androidreplaceandroid-navigationview

how to replace the Android NavigationView HeaderView


I have two different header xml layouts and want to switch between them programmatically. My problem is that the old layout is not replaced by the new but instead I end up with two header layouts. I read many Answers1 , Answer2 but it does not work.

Here´s what i try: and if i run this code 3 times I have 3 headers instead of replacing the header layout. I think I must delete the navigate.getHeaderView(0) first but how?

NavigationView navigate = (NavigationView) findViewById(R.id.navigation_view);
    navigate.getMenu().clear();
    navigate.inflateMenu(R.menu.menu_navigation_exit);
    navigate.inflateHeaderView(R.layout.navigation_view_header_exit);
    View header = navigate.getHeaderView(0);
    streetViewImage = (ImageView) header.findViewById(R.id.street_view_image);
    streetViewImage.set....
    ...

Solution

  • You need to save the reference of the header view and then remove it when you want to replace it with something else.

    navigate.removeHeaderView(previousHeaderView)