android-fragments 如何在导航控制器中获取当前显示的片段

i34xakig  于 2022-11-14  发布在  Android
关注(0)|答案(4)|浏览(230)

我使用了一个Activity,并将多个片段嵌入其中。现在我想知道在这个Activity类中,当前显示的是哪个片段。我该怎么做呢?我从这里看了一下解决方案How to know if a Fragment is Visible?

MyFragmentClass test = (MyFragmentClass) getSupportFragmentManager().findFragmentByTag("testID");
if (test != null && test.isVisible()) {
     //DO STUFF
}
else {
    //Whatever
}

但是我不知道参数"testID"是什么。进一步,我尝试从获取当前片段对象实现解决方案

Fragment currentFragment = getActivity().getFragmentManager().findFragmentById(R.id.fragment_container);

但在这里我得到了错误消息:“无法解析符号'fragment_container'”
在使用单个Activity和多个片段的方法时,有没有人知道如何获取当前显示的片段的名称?

anauzrmj

anauzrmj1#

我知道这里已经有2个答案了,但还有1个解决方案,所以我把它写在这里。代码如下:

NavController navController = Navigation.findNavController(this, R.id.fragment);
        int id=navController.getCurrentDestination().getId();
      if(id==R.id.startGameFragment ){ // change the fragment id
          selectedPosition(0);

      }else if(id==R.id.gameFragment ){ // change the fragment id
          selectedPosition(1);

      }else if(id==R.id.endGameFragment ){ // change the fragment id
          selectedPosition(2);

      }
l3zydbqr

l3zydbqr2#

您的第一个方法:

如果你想按标签查找片段,你需要先设置标签。你在做事务的时候做这个,例如:

getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, SheetEditorScreen.class, args, "testID" //Here you set the tag
)

然后您就可以像以前那样按标签获取片段:

getSupportFragmentManager().findFragmentByTag("testID");

您的第二种方法:

如果您想按id获取fragment,则需要传递容器的视图id,该id在Activity的布局xml文件中声明(在setContentView(R.id.main_activity)中设置):

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   xmlns:app="http://schemas.android.com/apk/res-auto">

   <androidx.fragment.app.FragmentContainerView
       android:id="@+id/fragment_container" <--- here is the id
       android:layout_width="match_parent"
       android:layout_height="match_parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

然后你就可以用下面的公式找到可见的片段:

getSupportFragmentManager().findFragmentById(R.id.fragment_container);
6yoyoihd

6yoyoihd3#

现在,由于我对您的问题有了更清楚的了解,我将添加另一个解决方案。该解决方案适用于FrameLayout和片段事务。但是,它也适用于NavController。请尝试以下代码:

public Fragment getCurrentlyVisibleFragment(){
    Fragment navHostFragment = getSupportFragmentManager().findFragmentById(R.id.navHostFragment);
    return navHostFragment == null ? null : navHostFragment.getChildFragmentManager().getFragments().get(0);
}
iecba09b

iecba09b4#

您可以执行以下操作:
1.在您的Activity中创建一个字段Fragment。如下所示:

private Fragment mCurrentlyDisplayingFragment;

1.每当改变片段时,只需将该片段对象传递给that。如下所示:

MyFragment fragment = new MyFragment();
// show it in the frame layout
mCurrentlyDisplayingFragment = fragment;

现在,无论何时检查,只要检查此字段即可。

相关问题