如何关闭在framelayout中加载的片段

时间:2017-12-18 13:58:21

标签: android android-fragments fragmentmanager android-framelayout

我使用这些行删除片段,我在结尾处获取日志,但这两行不起作用

DPFragment frag = new DPFragment();                     。getSupportFragmentManager()的BeginTransaction()除去(FRAG).commit();

这是我使用tab listner

的MainActivity
 tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {

            if(isActiveFrame){

                DPFragment frag = new DPFragment();
                getSupportFragmentManager().beginTransaction().remove(frag).commit();

                isActiveFrame =false;

            }else
            {

            }
        }

这是我的ActivityMain.xml

  <FrameLayout
    android:id="@+id/fl_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.example.myproject.externals.CustomViewPager
        android:id="@+id/vp_CustomViewPager"
        android:layout_height="match_parent"
        android:layout_width="match_parent" />

</FrameLayout>

我用这一行来加载fragement

getFragmentManager().beginTransaction().replace(R.id.fl_main, new DPFragment()).addToBackStack(null).commit();

2 个答案:

答案 0 :(得分:1)

而不是创建新的DPFragment实例DPFragment frag = new DPFragment();,而不是将其保存为类变量。

所以你的代码应该像

public class MainActivity extends Activity{
       private DPFragment frag;
       ...
           @Override
    protected void onCreate(Bundle savedInstanceState) {
        frag = new DPFragment();
        //use the DPFragment instance frag for adding it to CustomViewPager
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (isActiveFrame) {
               getSupportFragmentManager().beginTransaction().remove(frag).commit();
                    isActiveFrame = false;
                } else {
                }
            }
        }
    }
}

答案 1 :(得分:0)

我替换了

  getSupportFragmentManager().beginTransaction().remove(frag).commit();

带有

  if (getSupportFragmentManager().findFragmentById(R.id.fl_main) != null) {

                    getSupportFragmentManager().popBackStack();

                }

现在它完美无缺。