2

I am really new to android development. I have created a simple main activity and add an icon on top left. Clicking it I can show a blank fragment.on my screen replacing a layout which is loaded in onCreate method. Now clicking another icon I want to hide that fragment and load that layout again. How to do that?? any helps?? Below is my code

 //part of oncreate where my layout is loaded
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            }

     // part of code when icon clicked and fragment is loaded
             FragmentManager fragmentManager = getFragmentManager();
             FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
               BlankFragment  frag = new BlankFragment();
             fragmentTransaction.replace(R.id.content_main, frag);
                        fragmentTransaction.commit();

                        //another nearby icon clicked
    //now i want to replace this fragment from content_main layout

    //what code to add??  
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
nimra asad
  • 179
  • 6
  • 18

2 Answers2

4

If I got your question right, then this is the right answer I guess.

 //keep track of all fragments you add by tagging

 fragmentTransacaction.add(R.id.content, new FragA(), "first");

 //and when removeing
 Fragment f = getFragmentManager().findFragmentByTag("first");
 if(f!=null) fragmentTransac.remove(f);
 fragmentTransac.commit();

I got this from here

Community
  • 1
  • 1
0

You can toggle visibilty by below code.

public void toggleVisibility(Fragment fragment){

    FragmentTransaction transaction = getFragmentManager().beginTransaction();

    if (fragment.isHidden()) {
        transaction.show(fragment);
    } else {
        transaction.hide(fragment);
    }

    transaction.commit();
}
ugur
  • 3,604
  • 3
  • 26
  • 57