fragment remove issue

后端 未结 1 1176
北恋
北恋 2021-01-14 23:03

I am just learning fragments today. I press a button and it adds/removes a fragment. However if I try remove the fragment every fragment apart from the one I want removed is

相关标签:
1条回答
  • 2021-01-14 23:33

    You cant remove a Framgnet that you have added using the XML. If you want to remove the fragment via the .remove method you should first add it to your layout via the .add method, and not embed it into the XML file. in this case you can only .show or .hide the Fragments.

    UPDATE:

    To add the ButtonFragment dynamically do this:

    ButtonFragment buttonsFragment = new ButtonFragment();
    newfragmentTransaction = fragmentManager.beginTransaction();
    newfragmentTransaction.add(R.id.containerForFragments, buttonsFragment ).commit();
    

    UPDATE 2: This code:

      Button button = (Button) view.findViewById(R.id.button2);
        button.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
    
              ButtonFragment fragment = new ButtonFragment();
              if (fragment != null && fragment.isVisible()) {
    
    
    
                  FragmentManager fragmentManager = getFragmentManager();
    
                  FragmentTransaction transaction =  fragmentManager.beginTransaction(); 
                  transaction.remove(fragmentManager.findFragmentById(R.layout.activity_main)).commit();
    
              }
              else if(!fragment.isVisible())
              {
                  FragmentManager fragmentManager = getFragmentManager();
    
                  FragmentTransaction transaction =  fragmentManager.beginTransaction(); 
                  transaction.add(R.layout.activity_main, fragment ).commit();
              }       
    
          }
        });
    

    should be run from the Activity and not from the Fragment.

    0 讨论(0)
提交回复
热议问题