Home > Blockchain >  Show/Hide Fragment instead of replace
Show/Hide Fragment instead of replace

Time:12-02

I have 3 and more fragments and I want to access them with the drawer. So that when I click on "Profile" the current fragment(i.e. Home) should hide and "Profile" fragment should show and vice versa.. Right now its working with "replace fragment" but, Instead of replace I want to show/hide them when I click on the drawer button.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //my coding
    

    replace(new HomeFragment());
    init();
}

private void init() {
    mDrawer = (FlowingDrawer) findViewById(R.id.drawerlayout);
    iv_Menu = findViewById(R.id.iv_Menu);
    ll_Home = findViewById(R.id.ll_Home);
    ll_Profile = findViewById(R.id.ll_Profile);
    ll_Setting = findViewById(R.id.ll_Setting);
    ll_Share = findViewById(R.id.ll_Share);
    ll_Logout = findViewById(R.id.ll_Logout);

    iv_Menu.setOnClickListener(this);
    ll_Home.setOnClickListener(this);
    ll_Profile.setOnClickListener(this);
    ll_Setting.setOnClickListener(this);
    ll_Share.setOnClickListener(this);
    ll_Logout.setOnClickListener(this);


}

@Override
public void onClick(View view) {
    switch (view.getId()){
        case R.id.iv_Menu:
            mDrawer.openMenu(true);
            break;

        case R.id.ll_Home:
            replace(new HomeFragment(),"Home");
            mDrawer.closeMenu(true);
            break;

        case R.id.ll_Profile:
            replace(new ProfileFragment(),"Profile");
            mDrawer.closeMenu(true);
            break;

        case R.id.ll_Setting:
            startActivity(new Intent(this, SimplPreach.class));
            mDrawer.closeMenu(true);
            break;

        case R.id.ll_Share:
            Toast.makeText(this, "Share.", Toast.LENGTH_SHORT).show();
            mDrawer.closeMenu(true);
            break;

        case R.id.ll_Logout:
            Toast.makeText(this, "Logout.", Toast.LENGTH_SHORT).show();
            mDrawer.closeMenu(true);
            break;
    }
}

private void replace(Fragment fragment, String s) {
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.fl_Main,fragment);
    transaction.addToBackStack(s);
    transaction.commit();
}

private void replace(Fragment fragment) {
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.fl_Main,fragment);
    transaction.commit();
}

I have been searching from hours but nothing is working, How can I use show hide instead of replace .. Please help me..

CodePudding user response:

FragmentTransaction has the following methods you can use.

show(Fragment fragment)
hide(Fragment fragment)
add(int containerViewId, Fragment fragment, String tag)

And I think you don't need to call transaction.addToBackStack(s) in your case.

  • Related