android - Kotlin:片段内部的 FragmentManager 变为空
问题描述
这是我的代码:
Places.initialize(context!!, getString(R.string.google_api_key))
val autocompleteFragment : AutocompleteSupportFragment = fragmentManager?.findFragmentById(R.id.autocomplete_fragment) as AutocompleteSupportFragment
autocompleteFragment.setCountry("NO")
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.LAT_LNG, Place.Field.ADDRESS, Place.Field.ADDRESS_COMPONENTS))
autocompleteFragment.setOnPlaceSelectedListener(object : PlaceSelectionListener {
override fun onPlaceSelected(place: Place) {
onPlaceSelectedOverride(place)
Log.d("myTag", place.address + " - " + place.addressComponents + " - " + place.latLng)
}
override fun onError(status: Status) {
throw RuntimeException()
}
})
问题是片段管理器。之前代码放在mainActivity的onCreate()里面,代码就有这个区别。
val autocompleteFragment : AutocompleteSupportFragment = supportFragmentManager.findFragmentById(R.id.autocomplete_fragment) as AutocompleteSupportFragment
但是在将代码移动到另一个片段时,出现了各种各样的问题。fragmentManager 似乎为空。什么是片段管理器,我怎样才能使这个代码在片段中起作用?
解决方案
尝试使用 childFragmentManager
val autocompleteFragment : AutocompleteSupportFragment = childFragmentManager.findFragmentById(R.id.autocomplete_fragment) as AutocompleteSupportFragment
推荐阅读
- html - 对齐文本并将其环绕在图像旁边
- angular - 如何以角度 2 呈现从 WebAPI 获取的图像
- lua - 在 OpenWRT 上使用 Lighttpd 的 Lua
- excel - 即使在添加或删除行和列之后,VBA 也会引用相同的单元格
- laravel - 使用带参数的 Laravel Excel 导出 .xslx 数据
- javascript - 在使用 Quill.js 保存和重新加载数据时,我有哪些选择?
- python - 如何处理混合大小写正则表达式?
- docker - 如何确保 docker 确认优雅退出?
- python-3.x - 如何编码以重新排列列中的所有文本
- python-3.x - 线程安全删除python中的目录