我怀疑是不是SerachResultActivity的顺序问题。目前代码如下:package com.example.bus;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.Tip;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import java.util.ArrayList;
import java.util.List;
// 新增导入
import android.view.inputmethod.EditorInfo;
public class SearchResultActivity extends AppCompatActivity
implements PoiSearch.OnPoiSearchListener, GeocodeSearch.OnGeocodeSearchListener {
private Button searchBtn, goToBtn;
private RecyclerView resultListView;
private List<PoiItem> poiList = new ArrayList<>();
private ResultAdapter adapter;
private PoiSearch poiSearch;
// 地图相关
private MapView mapView;
private AMap aMap;
private Marker selectedMarker; // 终点标记
// 输入提示
private Inputtips inputTips;
private GeocodeSearch geocodeSearch;
// 当前城市
private String currentCity = "全国";
// 是否已与地图交互(防止重复居中)
private boolean userHasInteracted = false;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1001;
// 空状态提示视图
private TextView emptyView;
// 【关键新增】保存定位得到的“我的位置”
private double myCurrentLat = 0;
private double myCurrentLng = 0;
private boolean isLocationReady = false; // 定位是否完成
// 缓存从 HomeFragment 传来的关键词,等待定位完成后使用
private String pendingKeyword = null;
// ✅ 新增:将搜索输入框提升为成员变量
private android.widget.AutoCompleteTextView searchInput;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_result);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("搜索地点");
}
initViews();
setupMap(savedInstanceState);
setupSearchSuggestion();
try {
geocodeSearch = new GeocodeSearch(this);
geocodeSearch.setOnGeocodeSearchListener(this);
} catch (Exception e) {
e.printStackTrace();
}
// 只缓存 keyword,不立即搜索
pendingKeyword = getIntent().getStringExtra("keyword");
// 如果此时已经定位完成(比如权限已授权且地图加载快),可提前搜索
if (isLocationReady && pendingKeyword != null) {
runOnUiThread(() -> performSearchWithKeyword(pendingKeyword));
}
}
private void initViews() {
searchBtn = findViewById(R.id.search_btn);
resultListView = findViewById(R.id.result_list);
goToBtn = findViewById(R.id.btn_go_to);
emptyView = findViewById(R.id.empty_view);
searchInput = findViewById(R.id.search_input); // ✅ 初始化成员变量
goToBtn.setEnabled(false);
adapter = new ResultAdapter(poiList, this::onPoiItemSelected);
resultListView.setLayoutManager(new LinearLayoutManager(this));
resultListView.setAdapter(adapter);
resultListView.setVisibility(View.GONE);
emptyView.setVisibility(View.GONE);
// 修改:传递真实定位点
goToBtn.setOnClickListener(v -> {
if (selectedMarker == null) {
Toast.makeText(this, "请先选择一个位置", Toast.LENGTH_SHORT).show();
return;
}
LatLng targetPos = selectedMarker.getPosition();
// 确保定位已完成
if (!isLocationReady) {
Toast.makeText(this, "正在获取您的位置,请稍后再试", Toast.LENGTH_SHORT).show();
return;
}
Intent intent = new Intent(SearchResultActivity.this, RoutePlanActivity.class);
intent.putExtra("start_lat", myCurrentLat);
intent.putExtra("start_lng", myCurrentLng);
intent.putExtra("target_lat", targetPos.latitude);
intent.putExtra("target_lng", targetPos.longitude);
intent.putExtra(RoutePlanActivity.EXTRA_SOURCE, RoutePlanActivity.SOURCE_FROM_SEARCH_RESULT);
startActivity(intent);
finish();
});
}
private void setupMap(Bundle savedInstanceState) {
mapView = findViewById(R.id.map_view);
mapView.onCreate(savedInstanceState);
aMap = mapView.getMap();
if (aMap != null) {
initMapSettings();
} else {
new Handler(Looper.getMainLooper()).post(() -> {
aMap = mapView.getMap();
if (aMap != null) {
initMapSettings();
} else {
waitAMapReady();
}
});
}
}
private void waitAMapReady() {
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
int retry = 0;
@Override
public void run() {
if (mapView == null) return;
aMap = mapView.getMap();
if (aMap != null) {
initMapSettings();
} else if (retry++ < 30) {
new Handler(Looper.getMainLooper()).postDelayed(this, 100);
}
}
}, 100);
}
private void initMapSettings() {
UiSettings uiSettings = aMap.getUiSettings();
uiSettings.setZoomControlsEnabled(true);
uiSettings.setCompassEnabled(true);
uiSettings.setScrollGesturesEnabled(true);
uiSettings.setMyLocationButtonEnabled(true);
aMap.setOnMapClickListener(latLng -> {
onCustomLocationSelected(latLng);
});
// 初始视野:中国中心
new Handler(Looper.getMainLooper()).post(() ->
aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(35.8617, 104.1954), 4f))
);
enableMyLocationLayer();
}
private void enableMyLocationLayer() {
if (aMap == null) return;
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
MyLocationStyle myLocationStyle = new MyLocationStyle();
myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);
aMap.setMyLocationStyle(myLocationStyle);
aMap.setMyLocationEnabled(true);
AMap.OnMyLocationChangeListener listener = location -> {
if (location != null && !userHasInteracted) {
LatLng curLatlng = new LatLng(location.getLatitude(), location.getLongitude());
// 记录真实“我的位置”
myCurrentLat = location.getLatitude();
myCurrentLng = location.getLongitude();
isLocationReady = true;
aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(curLatlng, 16f));
userHasInteracted = true;
LatLonPoint point = new LatLonPoint(myCurrentLat, myCurrentLng);
RegeocodeQuery query = new RegeocodeQuery(point, 200, GeocodeSearch.AMAP);
try {
geocodeSearch.getFromLocationAsyn(query);
} catch (Exception e) {
e.printStackTrace();
}
// 定位完成后尝试搜索缓存的关键词
if (pendingKeyword != null) {
runOnUiThread(() -> performSearchWithKeyword(pendingKeyword));
}
aMap.setOnMyLocationChangeListener(null);
}
};
aMap.setOnMyLocationChangeListener(listener);
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
LOCATION_PERMISSION_REQUEST_CODE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
enableMyLocationLayer();
} else {
Toast.makeText(this, "定位权限被拒绝,部分功能受限", Toast.LENGTH_LONG).show();
currentCity = "全国";
}
}
}
private void setupSearchSuggestion() {
try {
inputTips = new Inputtips(this, new Inputtips.InputtipsListener() {
@Override
public void onGetInputtips(List<Tip> tipList, int rCode) {
if (rCode == 1000 && tipList != null && !tipList.isEmpty()) {
String[] arr = new String[tipList.size()];
for (int i = 0; i < tipList.size(); i++) {
arr[i] = tipList.get(i).getName();
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(
SearchResultActivity.this,
android.R.layout.simple_dropdown_item_1line,
arr
);
searchInput.setAdapter(adapter);
} else {
searchInput.setAdapter(null);
handleSearchError(rCode);
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
Handler handler = new Handler(Looper.getMainLooper());
Runnable[] pendingRunnable = {null};
searchInput.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (pendingRunnable[0] != null) {
handler.removeCallbacks(pendingRunnable[0]);
}
if (s.length() == 0) {
searchInput.setAdapter(null);
return;
}
pendingRunnable[0] = () -> {
new Handler(Looper.getMainLooper()).post(() -> {
try {
inputTips.requestInputtips(s.toString(), currentCity);
} catch (Exception e) {
e.printStackTrace();
}
});
};
handler.postDelayed(pendingRunnable[0], 600);
}
@Override
public void afterTextChanged(Editable s) {}
});
searchInput.setOnEditorActionListener((v, actionId, event) -> {
if ((actionId & EditorInfo.IME_MASK_ACTION) == EditorInfo.IME_ACTION_SEARCH) {
searchBtn.performClick();
return true;
}
return false;
});
searchBtn.setOnClickListener(v -> {
String keyword = searchInput.getText().toString().trim();
if (!keyword.isEmpty()) {
performSearch(keyword);
} else {
Toast.makeText(this, "请输入关键词", Toast.LENGTH_SHORT).show();
}
});
}
// ✅ 修改:先设置文本,再模拟点击按钮(等价于用户操作)
private void performSearchWithKeyword(String keyword) {
searchInput.setText(keyword);
searchInput.clearFocus();
searchBtn.performClick(); // ✅ 触发完整 UI 搜索流程
}
private void performSearch(String keyword) {
emptyView.setText("🔍 搜索中...");
emptyView.setVisibility(View.VISIBLE);
resultListView.setVisibility(View.GONE);
PoiSearch.Query query = new PoiSearch.Query(keyword, "", currentCity);
query.setPageSize(20);
query.setPageNum(0);
try {
poiSearch = new PoiSearch(this, query);
poiSearch.setOnPoiSearchListener(this);
poiSearch.searchPOIAsyn();
} catch (Exception e) {
Toast.makeText(this, "搜索失败", Toast.LENGTH_SHORT).show();
emptyView.setText("⚠️ 未找到相关地点");
}
}
private void handleSearchError(int rCode) {
String msg;
switch (rCode) {
case 12: msg = "API Key 错误"; break;
case 27: msg = "网络失败"; break;
case 30: msg = "SHA1/包名错误"; break;
case 33: msg = "请求频繁"; break;
default: msg = "错误码=" + rCode; break;
}
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
private void onPoiItemSelected(PoiItem item) {
LatLng latLng = new LatLng(item.getLatLonPoint().getLatitude(), item.getLatLonPoint().getLongitude());
if (selectedMarker != null) {
selectedMarker.remove();
selectedMarker = null;
}
selectedMarker = aMap.addMarker(new MarkerOptions()
.position(latLng)
.title("终点:" + item.getTitle())
.icon(com.amap.api.maps.model.BitmapDescriptorFactory.defaultMarker(
com.amap.api.maps.model.BitmapDescriptorFactory.HUE_RED)));
aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14f));
goToBtn.setEnabled(true);
}
private void onCustomLocationSelected(LatLng latLng) {
if (selectedMarker != null) {
selectedMarker.remove();
}
selectedMarker = aMap.addMarker(new MarkerOptions()
.position(latLng)
.title("终点:自定义位置")
.icon(com.amap.api.maps.model.BitmapDescriptorFactory.defaultMarker(
com.amap.api.maps.model.BitmapDescriptorFactory.HUE_RED)));
goToBtn.setEnabled(true);
}
@Override
public void onPoiSearched(PoiResult result, int rCode) {
if (rCode == 1000 && result != null && result.getPois() != null && !result.getPois().isEmpty()) {
List<PoiItem> newPoiList = result.getPois();
poiList.clear();
poiList.addAll(newPoiList);
adapter.notifyDataSetChanged();
resultListView.scrollToPosition(0);
resultListView.setVisibility(View.VISIBLE);
emptyView.setVisibility(View.GONE);
onPoiItemSelected(poiList.get(0));
} else {
emptyView.setText("⚠️ 未找到相关地点");
emptyView.setVisibility(View.VISIBLE);
resultListView.setVisibility(View.GONE);
}
}
@Override
public void onPoiItemSearched(PoiItem item, int rCode) {
// 必须实现
}
@Override
public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
if (rCode == 1000 && result != null && result.getRegeocodeAddress() != null) {
String city = result.getRegeocodeAddress().getCity();
currentCity = (city != null && !city.isEmpty()) ? city : result.getRegeocodeAddress().getProvince();
} else {
currentCity = "全国";
}
}
@Override
public void onGeocodeSearched(com.amap.api.services.geocoder.GeocodeResult geocodeResult, int i) {
// 忽略
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
inputTips = null;
geocodeSearch = null;
}
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
他应该在搜索之前请求出用户定位并且电视聚焦用户所在位置。但是我目前看到的是搜索出来结果后都没有这个流程
最新发布