我目前正在尝试在 PlacesFragment 中显示 PlaceAutocomplete 搜索栏。在 PlacesFragment 中,到目前为止我有:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PlaceAutocompleteFragment placeAutocompleteFragment = (PlaceAutocompleteFragment) getActivity().getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
placeAutocompleteFragment.setOnPlaceSelectedListener(
new PlaceSelectionListener() {
@Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
String placeDetailsStr = place.getName() + "\n"
+ place.getId() + "\n"
+ place.getLatLng().toString() + "\n"
+ place.getAddress() + "\n"
+ place.getAttributions();
Log.i("OnPlaceSelected", placeDetailsStr);
}
@Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i("OnPlaceSelected", "An error occurred: " + status);
}
}
);
}
我的 R.id.place_autocomplete_fragment 在 fragment_places.xml 文件中为:
<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:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="109dp" />
但是,我收到错误
“尝试在空对象引用上调用虚拟方法 'void com.google.android.gms.location.places.ui.PlaceAutocompleteFragment.setOnPlaceSelectedListener(com.google.android.gms.location.places.ui.PlaceSelectionListener)'”。
总的来说,我想知道这是否是在 PlacesFragment 中下一个 PlacesAutocompleteFragment 的正确方法,如果不是,我应该怎么做?提前致谢!