首先,只需确保现在所有片段都位于Android X最新库中即可。稍后,只需使用下一个:
MyFragment fragment = getFragmentManager()
.findFragmentByid(R.id.fragmentId);
,
使用导航和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
本文链接:https://www.f2er.com/3142199.html