'Back click listener for Google Places Address Search (AutocompleteSupportFragment)

enter image description hereIs there a way to capture the back button click listener from Google Places Address Search (AutocompleteSupportFragment)

  val btnBackClick =
            autocompleteFragment?.view?.findViewById(R.id.places_autocomplete_back_button) as androidx.appcompat.widget.AppCompatImageButton

        btnBackClick.setOnClickListener {
            Log.e("AutoComplete", "Address Search Back")
        }

Tried this leading to crash "java.lang.IllegalStateException: Places must be initialized."



Solution 1:[1]

I've tried to get the back button the same way you did on my end, but you are right, that View returns null even though it apparently exists: R.id.places_autocomplete_back_button.

Update: At the moment it is not currently possible to get this View, so I recommend you file a feature request for this in Google's Issue Tracker in case Google Engineers are able to consider adding this capability.

Hope this helps!

Solution 2:[2]

I had the same problem. I couldn't get a reference through neither the back button of the AutocompleteSupportFragment / onBackPressed listener / onBackPressedDispatcher from the activity, so I went on and used the error status instead.

// Assuming "autocompleteFragment" is the view name in your XML file
val fragment = supportFragmentManager.findFragmentById(R.id.autocompleteFragment) as AutocompleteSupportFragment
// ... 

fragment.setOnPlaceSelectedListener(object : PlaceSelectionListener {
    override fun onPlaceSelected(place: Place) {
        // Handle the result like usual
    }
    override fun onError(status: Status) {
        // Check if the user tapped the back button
        if (status == Status.RESULT_CANCELED) {
            // Do what you want to do when back button is pressed
        }
    }
}

Technically a workaround, but it does capture the back button flow.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2