我一直通过以下步骤尝试使用新的Places SDK应用Android Google Places自动完成功能:
添加的依赖项
implementation 'com.google.android.libraries.places:places:2.2.0'
implementation 'androidx.cardview:cardview:1.0.0'
添加的权限
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
在xml文件中
<androidx.cardview.widget.CardView
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/autocomplete_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="com.google.android.libraries.places.widget.AutocompleteSupportFragment"/>
</androidx.cardview.widget.CardView>
在我的活动文件中
// Initialize Places.
Places.initialize(getApplicationContext(), "My API KEY");
// Create a new Places client instance.
PlacesClient placesClient = Places.createClient(this);
// Initialize the AutocompleteSupportFragment.
AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment) getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);
// Specify the types of place data to return.
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME));
// Set up a PlaceSelectionListener to handle the response.
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
@Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
//Log.i(TAG, "Place: " + place.getName() + ", " + place.getId());
}
@Override
public void onError(Status status) {
// TODO: Handle the error.
//Log.i(TAG, "An error occurred: " + status);
}
});
问题是,当我尝试在搜索栏上键入任何键时,它会关闭搜索窗口。
注意:已启用API密钥,并且启用了API密钥后,我获得了已经在此项目中为“ Android Maps SDK”启用的API。
如果有人得到解决方案,请提供。
提前感谢。
此位置选择器方法已在2019年弃用。请按照最新方法实施位置选择器,这里是链接https://developers.google.com/places/android-sdk/client-migration