首页 > 解决方案 > 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 似乎为空。什么是片段管理器,我怎样才能使这个代码在片段中起作用?

标签: androidkotlin

解决方案


尝试使用 childFragmentManager

val autocompleteFragment : AutocompleteSupportFragment = childFragmentManager.findFragmentById(R.id.autocomplete_fragment) as AutocompleteSupportFragment

推荐阅读