首页 > 解决方案 > PlaceAutocompleteFragment 立即打开和关闭

问题描述

我正在尝试 PlaceAutocompleteFragment 里面Activity。我用过这个例子。它在 SearchBar 打开后立即关闭,我无法输入字母。我错过了什么?文件中添加的 ApiManifest和 Places API 已启用。

我的代码是。

活动:

public class MainActivity extends AppCompatActivity {

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



        final TextView txtVw = findViewById(R.id.placeName);

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

        /*AutocompleteFilter filter = new AutocompleteFilter.Builder()
                .setCountry("IN")
                .setTypeFilter(AutocompleteFilter.TYPE_FILTER_CITIES)
                .build();
        autocompleteFragment.setFilter(filter);*/
        autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
            @Override
            public void onPlaceSelected(Place place) {
                txtVw.setText(place.getName());
            }
            @Override
            public void onError(Status status) {
                txtVw.setText(status.toString());
            }
        });

    }
}

xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<android.support.v7.widget.CardView
    android:id="@+id/idCardView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:layout_marginTop="5dp"
    app:cardCornerRadius="4dp">
    <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" />
</android.support.v7.widget.CardView>
<TextView
    android:id="@+id/placeName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="No Place selected"
    android:textSize="20dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

标签: androidfragmentgoogle-places-api

解决方案


推荐阅读