使用 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