我当前正在尝试实例化导航抽屉中的片段。问题是过去我可以通过以下方式做到这一点:
MyFragment fragment = getSupportFragmentManager().findFragmentByid(R.id.fragmentId);
但是,现在在AndroidX支持库中,整个事情已经改变了,现在我不知道如何从NavController,NavigationUI或任何东西中检索片段。我需要实例化片段,以便可以在MainActivity的那些片段上实现接口,以便在它们之间进行通讯。
我正在使用Android Studio 3.5.1中的NavigationDrawer活动模板
答案 0 :(得分:0)
首先,只需确保现在所有片段都位于Android X最新库中即可。稍后,只需使用下一个:
MyFragment fragment = getFragmentManager()
.findFragmentByid(R.id.fragmentId);
答案 1 :(得分:0)
使用导航和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);
但是,建议将接口传递给Navigation世界中的Fragment的推荐模式是通过使用Fragments: Past, Present, and Future talk中讨论的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
,以相同的方式处理配置更改和初始创建后的重新创建。它还允许您使用FragmentScenario
(需要FragmentFactory
)test your Fragment in isolation