【问题标题】:Loading Fragment if not Null - Android如果不是 Null,则加载 Fragment - Android
【发布时间】:2016-04-10 17:39:46
【问题描述】:

我需要关于一个问题的帮助,在我正在开发的 Android 应用程序中,我一直在 Fragments 之间导航。我使用代码在Fragments 之间导航。

newsFeedFragment fragment = new newsFeedFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();

使用上面的代码,导航到从“onCreate”加载的新闻提要片段。您好,如果之前加载了片段,它应该显示之前加载的页面,应该跳过onCreate,但不跳过onResume。但是,如果在首次加载 Fragment 之前未加载 Fragment

谁能帮我实现这件事?

非常感谢

【问题讨论】:

  • 因为您需要为每个片段设置一些 id,然后搜索该片段(如果存在)加载它,否则创建新的然后加载它。如果您想要代码,我可以提供一些。
  • 你好 dex,如果你能给我看一个样本就太好了,我在 android 方面有点新。

标签: android fragment oncreate onresume


【解决方案1】:

您可以通过在片段中添加 TAG 来做到这一点。无论您在视图中添加片段的任何位置,都可以执行以下操作:

getSupportFragmentManager().beginTransaction().replace(R.id.something, new SomeFragment(),"SOMETAG").commit();

如果你想检查这个片段是否已经存在以防止重新加载它,请添加以下检查:

SomeFragment sf = (SomeFragment) getSupportFragmentManager().findFragmentByTag("SOMETAG");
if(sf != null)
{
   //the condition when the fragment is already exists
}
else
{
   //the condition when the fragment is not loaded
}

【讨论】:

  • 非常感谢Pooya,在if条件下,如果片段已经存在,我应该如何检索片段,如果不存在怎么办?有什么区别吗?抱歉问了太多问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-24
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
相关资源
最近更新 更多