简体   繁体   English

创建/销毁还是显示/隐藏片段?

[英]Create/destroy or show/hide Fragments?

I have a situation in which I need to show/hide a fragment based on a dynamic variable. 我有一种情况需要显示/隐藏基于动态变量的片段。 My question is should I create the fragment once, and then show/hide based on the variable. 我的问题是我应该创建片段一次,然后给出一个对变量/隐藏。 Or should I destroy/create it each time? 还是应该每次都销毁/创建它?

Create the fragment 创建片段

Fragment alertFragment = new AlertFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(android.R.id.content, alertFragment).commit();

After this should I call show/hide each time? 在此之后,我应该每次都调用show / hide吗?

getSupportFragmentManager().beginTransaction()
          .setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out)
          .show(alertFragment)  // or hide
          .commit();

Seems like a lot of work to show/hide something each time. 似乎每次都要显示/隐藏某些东西的工作很多。 Is this the right way to do it? 这是正确的方法吗?

I'd say that depends on weather it matters for your application if your Fragment is destroyed or not. 我想说,这取决于天气情况,无论您的Fragment是否被破坏,它对您的应用都很重要。

If it doesn't matter at all, simply replace the Fragment everytime by a new one. 如果没关系,只需每次都用一个新Fragment 替换 Fragment This is the simplest solution and does not require any logic. 这是最简单的解决方案,不需要任何逻辑。

Fragment f = new Fragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content, f).commit();

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

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