简体   繁体   English

启动片段时如何隐藏MainActivity布局?

[英]How to Hide MainActivity layout when fragment is launched?

I have a Main activity and I am launching a fragment from it. 我有一个主要活动,并且正在从中启动一个片段。 However when fragment is launched it also shows the layout of the main activity. 但是,启动片段时,它也会显示主要活动的布局。

what is the best way to stop it? 阻止它的最好方法是什么? I don't need to save its state it can be relaunched once fragment is closed. 我不需要保存其状态,一旦关闭片段,就可以重新启动它。

This is how am launching it 这就是启动方式

FragmentManager fragmentManager = getSupportFragmentManager();
            android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container, fragment);
            fragmentTransaction.addToBackStack("");
            fragmentTransaction.commit();

The best way to handle this kind of situation is to use two fragments ( FirstFragment will contain the Ui of ParentActivity ) and let the ParentAcivity contain just the FrameLayout as container. 处理这种情况的最好方法是使用两个片段( FirstFragment将包含的UI ParentActivity ),并让ParentAcivity只包含了FrameLayout作为容器。 And then you can keep replacing fragments in that container without any problem. 然后,您可以继续替换该容器中的片段,而不会出现任何问题。

1.put 1.放

findViewById(R.id.xxx).setVisibility(View.GONE); 

before getSupportFragmentManager... to hide the view on activity that you want to hide 在getSupportFragmentManager之前...以隐藏要隐藏的活动的视图

2.override onBackPressed() to come back from fragment to activity 2.重写onBackPressed()从片段回到活动

@override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0 ) {
        findViewById(R.id.xxx).setVisibility(View.VISIBLE);
        getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }
    else {
        super.onBackPressed();
    }

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM