PlaceAutocompleteFragment disappears on click

2019-02-28 20:12发布

问题:

I wanted to implement AutocompleteTextView (google places) but when I click to searchView in a fragment, the fragment disappears (fell down).

My code:

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_autocomplete);

        PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);

        AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
                .setTypeFilter(AutocompleteFilter.TYPE_FILTER_CITIES)
                .build();

        autocompleteFragment.setFilter(typeFilter);

        autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {

            @Override
            public void onPlaceSelected(com.google.android.gms.location.places.Place place) {
                // TODO: handle click
            }

            @Override
            public void onError(Status status) {
                // TODO: Handle the error.
            }
        });

    }

xml:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="ui.screen.activity.AutocompleteActivity">

    <fragment
        android:id="@+id/place_autocomplete_fragment"
        android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</RelativeLayout>

Thanks for any advice

回答1:

I had the same problem. I messed up a little bit with the API Console https://console.developers.google.com/ enabling the Maps API AND the Places API for Android and now it's working fine.