如何阻止当前选定的片段重新加载到导航抽屉中

Bid*_*han 2 android android-fragments

我有一个包含4个项目的“导航”抽屉,每个项目在单击时都会加载4个不同的片段。所有片段都包含一个列表视图,该列表视图显示使用AsyncTask从Web提取的数据。我的问题是:假设我单击第二项,该片段加载就好了。但是,当我再次单击同一项目时,该片段也会再次加载。有什么办法可以阻止当前选择的片段再次加载?也许我可以通过某种方式禁用单击当前选中的项目。我相信肯定有更好的方法。谢谢。

reV*_*rse 5

您可能正在将您添加FragmentFrameLayout或任何其他类型的容器中。在开始事务并替换容器中的Fragment之前,您可以通过以下代码检查您要添加的Fragment是否已经存在:

private void openFragment(Fragment newFragment){
    Fragment containerFragment = getFragmentManager().findFragmentById(R.id.container);
    if (containerFragment.getClass().getName().equalsIgnoreCase(newFragment.getClass().getName()))
       return;
    else
       // Start transaction and replace fragment
}
Run Code Online (Sandbox Code Playgroud)