-1

我目前正在尝试从导航抽屉实例化片段。问题是,过去我可以通过以下方式做到这一点:

MyFragment fragment = getSupportFragmentManager().findFragmentByid(R.id.fragmentId);

但现在在 AndroidX 支持库中,整个事情都发生了变化,现在我不知道如何从 NavController、NavigationUI 或其他任何地方检索片段。我需要实例化我的片段,以便我可以在 MainActivity 的这些片段上实现接口,以便在它们之间进行片段通信。

我正在使用来自 Android Studio 3.5.1 的 NavigationDrawer 活动模板

4

2 回答 2

0

首先,只需确保您的所有片段现在都在最新的 Android X 库中。稍后,只需使用下一个:

MyFragment fragment = getFragmentManager()
      .findFragmentByid(R.id.fragmentId);
于 2019-11-07T19:10:13.617 回答
0

使用 Navigation 和 a时,您的 Fragments 是布局NavHostFragment中的子片段。NavHostFragment

Fragment navHostFragment = getSupportFragmentManager().findFragmentById(
    R.id.nav_host_fragment); // Whatever your ID in your layout is
FragmentManager childFragmentManager = navHostFragment.getChildFragmentManager();
// Now you can get your Fragment from the childFragmentManager
MyFragment fragment = childFragmentManager.findFragmentByid(R.id.fragmentId);

但是,在导航世界中将接口传递给 Fragments 的推荐模式是通过使用Fragments:Past、Present 和 Future 谈话FragmentFactory中讨论的构造函数注入:

// Create an interface for what methods you want to expose
interface Callback {
  // whatever methods you want
}

// Change your Fragment to take in that interface
class MyFragment(val callback: Callback) : Fragment() {
    // Now your Fragment always has a reference to the Callback
}

private class MyActivityFactory(
    callback: Callback
) : FragmentFactory() {
    override fun instantiate(
        classLoader: ClassLoader,
        className: String
    ) = when (className) {
        MyFragment::class.java.name -> MyFragment(callback)
        else -> super.instantiate(classLoader, className)
    }
}

// Now update your MyActivity to implement the interface
// and pass itself into an instance of the FragmentFactory you created
class MyActivity : AppCompatActivity(), Callback {
    override fun onCreate(savedInstanceState: Bundle?) {
        supportFragmentManager.fragmentFactory =
            MyActivityFactory(this)
        super.onCreate(savedInstanceState)
        ...
    }
}

通过使用FragmentFactory,配置更改后的重新创建和初始创建以相同的方式处理。它还允许您使用(需要 a )单独测试您的 FragmentFragmentScenarioFragmentFactory

于 2019-11-08T18:22:28.153 回答