Android: fragments overlapping issue

前端 未结 17 1479
闹比i
闹比i 2020-11-27 17:49

I am facing a problem of overlapping fragments when i switch between tabs and attach fragments to a tab view below is my code please help

public class Fragme         


        
17条回答
  •  孤城傲影
    2020-11-27 17:58

    I also faced fragment overlapping issue.Here is how I solved it -

    1) We need to add the first fragment with addToBackStack, so that it is retained in the stack -

    FirstFragment firstFragment = new FirstFragment();
    getFragmentManager().beginTransaction().add(R.id.fragment_container, firstFragment).addToBackStack("first frag").commit();
    

    2) While adding the second fragment, replace the first fragment rather then adding it.Since the first fragment was already added in the stack, so it will be present when you press back from second fragment -

    SecondFragment secondFragment= new SecondFragment();
    getFragmentManager().beginTransaction().replace(R.id.fragment_container, secondFragment).addToBackStack("second frag").commit();
    

    3) Here is how back press can be handled, below code should be present in the parent Activity -

     public void onBackPressed(){
        if(getFragmentManager().getBackStackEntryCount() <= 1){
           super.onBackPressed();
        } else {
           getFragmentManager().popBackStack();
        }
     }
    

提交回复
热议问题