如何获取导航控制器中当前显示的片段
我使用单个活动并将多个片段嵌入其中。现在我想知道在单个活动类中,当前正在显示哪个片段。我该怎么做?我从这里查看了解决方案 如何知道片段是否可见?
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'”
有谁知道如何获取使用单个活动时显示的当前片段的名称和多个片段方法?
I use a singe activity and embed multiple fragments into it. Now I would like to know within the single activity class, which Fragment is currently being displayed. How can I do this? I had a look at the solution from here How to know if a Fragment is Visible?
MyFragmentClass test = (MyFragmentClass) getSupportFragmentManager().findFragmentByTag("testID");
if (test != null && test.isVisible()) {
//DO STUFF
}
else {
//Whatever
}
But I don't know what to you for the parameter "testID"
. Further, I tried to implement the solution from Get the current fragment object
Fragment currentFragment = getActivity().getFragmentManager().findFragmentById(R.id.fragment_container);
But here I get the error message: "Cannot resolve symbol 'fragment_container'"
Does anyone have an idea how to get the name of the current Fragment that is being displayed when using a single activity and multiple fragments approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我知道这里已经有 2 个答案,但还有 1 个解决方案,所以我将其写在这里。这是代码:
I know there are already 2 answers on mine here but still have 1 more solution so I am writing it here. This is the code:
您的第一个方法:
如果您想通过标签找到片段,则需要先设置标签。进行交易时,您可以这样做,因为ex:
,然后您将能够像您一样通过标签获得片段:
您的第二种方法:
如果您想要通过ID获取片段,您需要传递您在活动的布局XML文件中声明的容器视图ID(
setContentView(r.id.main_activity)
):,您可以找到可见的片段与:
Your 1st approach:
If you want to find fragment by tag you need to set the tag first. You do it while making transaction, for ex:
and then you will be able to get fragment by tag as you did:
Your 2nd approach:
If you want to get fragment by id you need to pass container's view id which you declare in your activity's layout xml file (set in
setContentView(R.id.main_activity)
):and then you can find the visible fragment with:
现在,因为我对您的问题更加清楚,所以我添加了另一个解决方案。它与
framelayout
和片段交易一起使用。但是,这也将与navController
一起使用。尝试此代码:Now, because I get clearer about your problem, I am adding another solution. That worked with
FrameLayout
and fragment transaction. But, this will work withNavController
also. Try this code:您可以做类似的事情:
fragment
的字段。这样:现在,只要您检查一下,只需检查此字段。
You can do something like this:
Fragment
in your activity. Like this:Now, whenever you are checking, just check this field.