【问题标题】:how to remove fragment over an activity layout如何删除活动布局上的片段
【发布时间】:2017-04-01 13:30:54
【问题描述】:

我对 android 开发真的很陌生。我创建了一个简单的主要活动并在左上角添加了一个图标。单击它我可以显示一个空白片段。在我的屏幕上替换在 onCreate 方法中加载的布局。现在单击另一个图标,我想隐藏该片段并再次加载该布局。怎么做??有什么帮助吗?? 下面是我的代码

 //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??  

【问题讨论】:

    标签: android android-layout android-fragments fragmentmanager


    【解决方案1】:

    如果我的问题是正确的,那么我猜这就是正确的答案。

     //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();
    

    我从here得到这个

    【讨论】:

      【解决方案2】:

      您可以通过以下代码切换可见性。

      public void toggleVisibility(Fragment fragment){
      
          FragmentTransaction transaction = getFragmentManager().beginTransaction();
      
          if (fragment.isHidden()) {
              transaction.show(fragment);
          } else {
              transaction.hide(fragment);
          }
      
          transaction.commit();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多