我目前正在尝试向我的 Google 地图应用添加自动完成搜索栏。我想用它来缩放到搜索的目的地。到目前为止,这适用于我当前的解决方案,但仍然缺少自动完成功能,我希望在搜索栏中有一个小“X”按钮来清除文本。必须有比我目前的方法更好的解决方案,因为到目前为止它真的很原始。 这是我的activity_maps.xml_
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:orientation="horizontal">
<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4"
android:hint="Search Location Here" />
<Button
android:id="@+id/search_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:onClick="onMapSearch"
android:text="Search" />
</LinearLayout>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:focusableInTouchMode="true"
android:background="@color/dark_green"
tools:context=".MapsActivity"
android:focusable="true" />
</LinearLayout>
和我的函数 onMapSearch():
fun onMapSearch(view: View?) {
try {
//finding editText by id
locationSearch.isCursorVisible = true
locationSearch.setOnClickListener(View.OnClickListener {
locationSearch.isCursorVisible = true
})
val location = locationSearch.text.toString()
var addressList: List<Address>? = null
if (location != null || location != "") {
val geocoder = Geocoder(this)
try {
//finding the address of the searched place
addressList = geocoder.getFromLocationName(location, 1)
} catch (e: IOException) {
e.printStackTrace()
}
val address: Address = addressList!![0]
val latLng = LatLng(address.getLatitude(), address.getLongitude())
//moving camera to the given position
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17.5f))
//set cursor in search bar visible
locationSearch.isCursorVisible = false
//calling function to hide keyboard after search
}
} catch (e: java.lang.Exception) {
println("searching for unknown location")
}
}