放置自動完成整合
Google Places API for Android 中的自動填充功能可為使用者提供位置預測。當使用者在搜尋框中輸入內容時,自動填充功能會根據使用者的查詢顯示位置。
AutoCompleteActivity.java
private TextView txtSelectedPlaceName;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_autocomplete);
txtSelectedPlaceName = (TextView) this.findViewById(R.id.txtSelectedPlaceName);
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.fragment_autocomplete);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
@Override
public void onPlaceSelected(Place place) {
Log.i(LOG_TAG, "Place: " + place.getName());
txtSelectedPlaceName.setText(String.format("Selected places : %s - %s" , place.getName(), place.getAddress()));
}
@Override
public void onError(Status status) {
Log.i(LOG_TAG, "An error occurred: " + status);
Toast.makeText(AutoCompleteActivity.this, "Place cannot be selected!!", Toast.LENGTH_SHORT).show();
}
});
}
}
activity_autocomplete.xml
<fragment
android:id="@+id/fragment_autocomplete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/txtSelectedPlaceName"
android:layout_margin="20dp"
android:padding="15dp"
android:hint="@string/txt_select_place_hint"
android:textSize="@dimen/place_autocomplete_prediction_primary_text"/>