findFragmentById 总是返回 null [英] findFragmentById always returns null

查看:48
本文介绍了findFragmentById 总是返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 xml 布局中为我的片段定义一个 ID:

I'm defining an ID for my fragment in the xml layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/test_fragment"
...

然后我在活动的 onCreate 方法中添加这个片段:

Then I add this fragment in the activity's onCreate method:

MyFragment myFragment = new MyFragment();
fragmentTransaction.add(R.id.fragment_container, myFragment);
fragmentTransaction.commit();

这一切正常.替换fragments,也在工作.

This is all working fine. Replacing fragments and is also working.

稍后我尝试在活动的方法之一中通过其 ID 检索此片段:

Later I'm trying to retrieve this fragment by its ID in one of the activity's methods:

MyFragment myFragment = (MyFragment) getFragmentManager().findFragmentById(R.id.test_fragment);

这样做会导致 myFragment 为 null.总是.

Doing so leads to myFragment being null. Always.

当我尝试对标签而不是 ID 执行相同操作时,我可以通过标签检索片段而不会出现任何问题:

When I try to do the same with tags instead of IDs I can retrieve the fragment by its tag without any problems:

MyFragment myFragment = new MyFragment();
fragmentTransaction.add(R.id.fragment_container, myFragment, "testfragment");
fragmentTransaction.commit();

...

MyFragment myFragment = (MyFragment) getFragmentManager().findFragmentByTag("testfragment");

为什么 findFragmentById 找不到片段,而 findFragmentByTag 却能找到?我错过了什么吗?

Why can't findFragmentById find the fragment, but findFragmentByTag does so? Am I missing something?

推荐答案

R.id.test_fragment 不是你的片段的 ID,而是你的 LinearLayout 的 id

R.id.test_fragment is not the ID of your fragment but the id of your LinearLayout

调用 add(int containerViewId, Fragment fragment) 将添加一个没有标签的片段.因此,或者您使用 add(int containerViewId, Fragment fragment, String tag) 并使用您的标签(作为 ID)取回您的片段

Calling add(int containerViewId, Fragment fragment) will add a fragment without a tag. So or you use add(int containerViewId, Fragment fragment, String tag) and you get back your fragment using your tag (as an ID)

这篇关于findFragmentById 总是返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆