gpt4 book ai didi

android - 迁移到 AndroidX 后,findFragmentById 为 fragment 返回 null

转载 作者:行者123 更新时间:2023-11-29 23:19:53 24 4
gpt4 key购买 nike

迁移到 AndroidX 后,当我尝试获取 fragment 时,findFragmentById(还有 findFragmentByTag)开始返回 null。

像这样在 XML 中添加 fragment :

    <fragment
android:id="@+id/id_fragment"
android:tag="tag_fragment"
android:name="com.blaa.MyFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

fragment 看起来像这样:

class MyFragment : androidx.fragment.app.Fragment() {
...
}

Activity 看起来像这样:

class MyActivity : AppCompatActivity(){
...
}

依赖关系:

...
implementation "androidx.appcompat:appcompat:1.0.2"
implementation "androidx.legacy:legacy-support-v4:1.0.0"
implementation "com.google.android.material:material:1.1.0-alpha03"
...

下面是我在代码中的调用方式:

supportFragmentManager.findFragmentById(R.id.id_fragment)

supportFragmentManager.findFragmentByTag(R.id.tag_fragment)

两者都返回空值。我也试过只使用 fragmentManager,结果为空 而且它无论如何都不会工作,因为它返回简单的 fragment ,而不是 androidx fragment 。

谢谢你的建议

最佳答案

索引访问,类似于 fm.getFragments().get(0)fm.getFragments().get(1),可能会起作用。

如果没有……它可能找不到它,因为它还没有被添加(时间问题)。

fm.getFragments() 至少有用,可以查看当前时间点甚至可用的内容。

关于android - 迁移到 AndroidX 后,findFragmentById 为 fragment 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54541839/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com