Kotlin:片段内的FragmentManager变为null

时间:2019-05-10 14:57:53

标签: android kotlin

这是我的代码:

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()
            }
        })

问题是fragmentManager。以前,代码被放置在mainActivity的onCreate()内部,并且代码具有这种区别。

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

但是在将代码移至另一个片段时,出现了各种问题。 fragmentManager似乎为空。什么是fragmentManager,如何使此代码在片段中起作用?

3 个答案:

答案 0 :(得分:0)

不确定是否要使用嵌套片段,但如果是这样,则可以尝试使用childFragmentManager。

答案 1 :(得分:0)

尝试一下:

val autocompleteFragment : AutocompleteSupportFragment = activity!!supportFragmentManager.findFragmentById(R.id.autocomplete_fragment) as AutocompleteSupportFragment

答案 2 :(得分:0)

尝试使用childFragmentManager

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