关于Toast连点显示不及时的问题

有时候我们需要使用Toast显示信息,快了之后似乎不能及时显示我们想要弹出的信息, 因为Toast的显示是压栈的. 如果使用单例可解决这一问题.上代码, 很简单.

 1 package com.fyc.util;
 2 
 3 import android.content.Context;
 4 import android.widget.Toast;
 5 
 6 public class ToastUtils {
 7 
 8     private static Toast mToast;
 9     
10     public static void show(Context ctx, String text) {
11         if (mToast == null) {
12             mToast = Toast.makeText(ctx, text, Toast.LENGTH_SHORT);
13         } else {
14             mToast.setText(text);
15         }
16         mToast.show();
17     }
18 }

如果是自定的布局也是一样.  

转载于:https://www.cnblogs.com/fangyucun/archive/2013/05/25/3098510.html

那现在,我还是有搜索问题。你提供的代码,好像搜索之后程序会卡顿。上文提到了那个RoutePlanActivity,你给代码package com.example.bus; import android.os.Bundle; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.amap.api.maps.AMap; import com.amap.api.maps.MapView; import com.amap.api.services.core.LatLonPoint; import com.amap.api.services.route.BusPath; import com.amap.api.services.route.BusRouteResult; import com.amap.api.services.route.DriveRouteResult; import com.amap.api.services.route.RideRouteResult; import com.amap.api.services.route.RouteResult; import com.amap.api.services.route.RouteSearch; import com.amap.api.services.route.WalkRouteResult; public class RoutePlanActivity extends AppCompatActivity implements RouteSearch.OnRouteSearchListener { private MapView mapView; private AMap aMap; private RouteSearch routeSearch; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_route_plan); mapView = findViewById(R.id.map_view); mapView.onCreate(savedInstanceState); if (aMap == null) aMap = mapView.getMap(); try { routeSearch = new RouteSearch(this); routeSearch.setRouteSearchListener(this); } catch (Exception e) { e.printStackTrace(); Toast.makeText(this, "路线服务初始化失败,请检查依赖", Toast.LENGTH_LONG).show(); finish(); return; } parseIntentAndStartSearch(); } private void parseIntentAndStartSearch() { String startMode = getIntent().getStringExtra("start_mode"); double targetLat = getIntent().getDoubleExtra("target_lat", 0); double targetLng = getIntent().getDoubleExtra("target_lng", 0); if (targetLat == 0 || targetLng == 0) { Toast.makeText(this, "目标位置无效", Toast.LENGTH_SHORT).show(); finish(); return; } // 构造目标 com.amap.api.services.core.LatLonPoint startPoint, targetPoint; if ("my_location".equals(startMode)) { // TODO: 实际应使用定位获取“我的位置” // 这里模拟北京某坐标 startPoint = new com.amap.api.services.core.LatLonPoint(39.909186, 116.397411); } else { double startLat = getIntent().getDoubleExtra("start_lat", 0); double startLng = getIntent().getDoubleExtra("start_lng", 0); startPoint = new com.amap.api.services.core.LatLonPoint(startLat, startLng); } targetPoint = new com.amap.api.services.core.LatLonPoint(targetLat, targetLng); RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(startPoint, targetPoint); RouteSearch.BusRouteQuery query = new RouteSearch.BusRouteQuery(fromAndTo, RouteSearch.BUS_DEFAULT, "", 0); // ✅ 第2步:加 try-catch 防止 Unhandled Exception try { routeSearch.calculateBusRouteAsyn(query); } catch (Exception e) { Toast.makeText(this, "路线查询启动失败", Toast.LENGTH_SHORT).show(); } } @Override public void onBusRouteSearched(BusRouteResult result, int rCode) { if (rCode == 1000 && result != null && result.getPaths() != null && !result.getPaths().isEmpty()) { BusPath best = result.getPaths().get(0); Toast.makeText(this, "推荐路线:" + best.getDuration() / 60 + "分钟,步行" + best.getWalkDistance() + "米", Toast.LENGTH_LONG).show(); // TODO: 绘制路线(后续可加 Polyline 或 RouteOverlay) } else { Toast.makeText(this, "未找到公交路线", Toast.LENGTH_SHORT).show(); } } @Override public void onDriveRouteSearched(DriveRouteResult result, int rCode) { // 空实现(原已有) } // ✅ 第3步:新增空实现方法 - onWalkRouteSearched @Override public void onWalkRouteSearched(WalkRouteResult result, int rCode) { // 空实现 } // ✅ 第3步:新增空实现方法 - onRideRouteSearched @Override public void onRideRouteSearched(RideRouteResult result, int rCode) { // 空实现 } // ---------------- 生命周期方法 ---------------- @Override protected void onResume() { mapView.onResume(); super.onResume(); } @Override protected void onPause() { mapView.onPause(); super.onPause(); } @Override protected void onDestroy() { mapView.onDestroy(); super.onDestroy(); } @Override protected void onSaveInstanceState(Bundle outState) { mapView.onSaveInstanceState(outState); super.onSaveInstanceState(outState); } }
11-07
var window = floaty.window( <vertical> <text id="coords" text="击坐标: (0, 0)" textSize="16sp" /> <input id="input" text="请输入你的名字" textSize="16sp" focusable="true" /> <button id="ok" text="确定" /> <button id="toggle" text="开启坐标显示" textColor="#000000" /> <horizontal> <text text="时间间隔(ms):" textSize="14sp" /> <input id="interval" text="1000" inputType="number" textSize="14sp" /> </horizontal> <horizontal> <text text="击次数:" textSize="14sp" /> <input id="count" text="10" inputType="number" textSize="14sp" /> </horizontal> <horizontal> <text text="击坐标(x,y):" textSize="14sp" /> <input id="coordsInput" text="100,100" textSize="14sp" /> </horizontal> <button id="autoClick" text="连按钮" textColor="#000000" /> </vertical> ); ui.run(() => { window.exitOnClose(); toast("长按确定键可调整位置"); // 监听触摸事件并在悬浮窗中显示坐标 events.observeTouch(); window.toggle.on("click", () => { isTracking = !isTracking; if (isTracking) { window.toggle.setText("关闭坐标显示"); window.toggle.setTextColor(android.graphics.Color.RED); } else { window.toggle.setText("开启坐标显示"); window.toggle.setTextColor(android.graphics.Color.BLACK); window.coords.setText("击坐标: (0, 0)"); // 重置坐标显示 } }); events.on("touch", (point) => { if (isTracking) { let x = Math.floor(point.x); let y = Math.floor(point.y); window.coords.setText(`击坐标: (${x}, ${y})`); } }); window.input.on("key", function (keyCode, event) { if (event.getAction() == event.ACTION_DOWN && keyCode == keys.back) { window.disableFocus(); event.consumed = true; } }); window.input.on("touch_down", () => { window.requestFocus(); window.input.requestFocus(); });帮我加个最小化按钮功能
04-02
说这个问题了,现在我的项目进行到这一步之后,就差搜索以及规划路线的功能了,你提供的SearchResultActivity是是存在问题,因为每次搜索都会很卡顿而且搜索到结果,这部分代码如下:package com.example.bus; import android.content.Intent; import android.os.Bundle; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; 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.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 java.util.ArrayList; import java.util.List; public class SearchResultActivity extends AppCompatActivity implements PoiSearch.OnPoiSearchListener { private EditText searchInput; 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; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search_result); // 设置 ActionBar 返回按钮 if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle("搜索地"); } initViews(); setupMap(savedInstanceState); // 初始化地图 setupSearch(); // 初始化搜索 } private void initViews() { searchInput = findViewById(R.id.search_input); searchBtn = findViewById(R.id.search_btn); resultListView = findViewById(R.id.result_list); goToBtn = findViewById(R.id.btn_go_to); goToBtn.setEnabled(false); } private void setupMap(Bundle savedInstanceState) { mapView = findViewById(R.id.map_view); mapView.onCreate(savedInstanceState); if (aMap == null) { aMap = mapView.getMap(); UiSettings uiSettings = aMap.getUiSettings(); uiSettings.setZoomControlsEnabled(true); uiSettings.setCompassEnabled(true); uiSettings.setScrollGesturesEnabled(true); aMap.setOnMapClickListener(latLng -> { if (selectedMarker != null) selectedMarker.remove(); selectedMarker = aMap.addMarker(new MarkerOptions() .position(latLng) .title("选中位置")); goToBtn.setEnabled(true); }); aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(39.909186, 116.397411), 10f)); } } private void setupSearch() { String keyword = getIntent().getStringExtra("keyword"); if (keyword != null && !keyword.isEmpty()) { searchInput.setText(keyword); performSearch(keyword); } searchBtn.setOnClickListener(v -> { String text = searchInput.getText().toString().trim(); if (!text.isEmpty()) { performSearch(text); } else { Toast.makeText(this, "请输入关键词", Toast.LENGTH_SHORT).show(); } }); goToBtn.setOnClickListener(v -> { if (selectedMarker != null) { LatLng pos = selectedMarker.getPosition(); navigateToRoute(pos.latitude, pos.longitude, "地图选"); } else if (!poiList.isEmpty()) { PoiItem item = poiList.get(0); LatLonPoint p = item.getLatLonPoint(); navigateToRoute(p.getLatitude(), p.getLongitude(), item.getTitle()); } else { Toast.makeText(this, "暂无目标位置", Toast.LENGTH_SHORT).show(); } }); } private void navigateToRoute(double lat, double lng, String title) { Intent intent = new Intent(this, RoutePlanActivity.class); intent.putExtra("start_mode", "my_location"); intent.putExtra("target_lat", lat); intent.putExtra("target_lng", lng); intent.putExtra("target_title", title); startActivity(intent); } private void performSearch(String keyword) { PoiSearch.Query query = new PoiSearch.Query(keyword, "15", "全国"); // 公共交通大类 query.setPageSize(20); query.setPageNum(0); try { poiSearch = new PoiSearch(this, query); poiSearch.setOnPoiSearchListener(this); poiSearch.searchPOIAsyn(); } catch (Exception e) { e.printStackTrace(); Toast.makeText(this, "搜索启动失败", Toast.LENGTH_SHORT).show(); } } @Override public void onPoiSearched(PoiResult result, int rCode) { if (rCode == 1000 && result != null && result.getPois() != null) { poiList.clear(); poiList.addAll(result.getPois()); if (adapter == null) { adapter = new ResultAdapter(poiList, item -> { if (selectedMarker != null) selectedMarker.remove(); LatLng latLng = new LatLng(item.getLatLonPoint().getLatitude(), item.getLatLonPoint().getLongitude()); selectedMarker = aMap.addMarker(new MarkerOptions().position(latLng).title(item.getTitle())); aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14f)); goToBtn.setEnabled(true); }); resultListView.setLayoutManager(new LinearLayoutManager(this)); resultListView.setAdapter(adapter); } else { adapter.notifyDataSetChanged(); } goToBtn.setEnabled(!poiList.isEmpty()); } else { String msg = rCode == 17 ? "高德Key校验失败" : "搜索失败: 错误码=" + rCode; Toast.makeText(this, msg, Toast.LENGTH_LONG).show(); } } @Override public void onPoiItemSearched(PoiItem item, int rCode) {} @Override protected void onResume() { super.onResume(); mapView.onResume(); } @Override protected void onPause() { super.onPause(); mapView.onPause(); } @Override protected void onDestroy() { super.onDestroy(); mapView.onDestroy(); if (poiSearch != null) poiSearch.setOnPoiSearchListener(null); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mapView.onSaveInstanceState(outState); } @Override public boolean onSupportNavigateUp() { onBackPressed(); return true; } }
11-08
你提醒我了,MapFragment代码如下:package com.example.bus.ui.map; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import com.amap.api.maps.MapView; import com.amap.api.maps.AMap; import com.amap.api.maps.model.LatLng; //import com.example.bus.R; //import com.example.bus.databinding.FragmentMapBinding; import com.amap.api.services.core.AMapException; import com.amap.api.maps.CameraUpdateFactory; import com.amap.api.maps.UiSettings; import com.amap.api.services.poisearch.PoiResult; import com.amap.api.services.poisearch.PoiSearch; import com.example.bus.R; import com.example.bus.RoutePlanActivity; import com.example.bus.databinding.FragmentMapBinding; import com.amap.api.services.core.PoiItem; import com.amap.api.services.core.LatLonPoint; // MapView 已在 XML 中声明,无需额外 import(会自动识别) public class MapFragment extends Fragment { private FragmentMapBinding binding; private MapView mapView; // 高德地图视图 private AMap aMap; // 地图控制器 private boolean isFirstLocationSet = false; // 防止反复跳转 @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // 初始化 ViewModel 和 ViewBinding binding = FragmentMapBinding.inflate(inflater, container, false); View root = binding.getRoot(); //绑定 MapView mapView = root.findViewById(R.id.map_view); mapView.onCreate(savedInstanceState); // 必须调用生命周期方法 // 初始化地图 initMap(); if (binding.mapSearch != null) { binding.mapSearch.setOnClickListener(v -> { String keyword = binding.mapInput2.getText().toString().trim(); if (keyword.isEmpty()) { Toast.makeText(requireContext(), "请输入终", Toast.LENGTH_SHORT).show(); return; } PoiSearch.Query query = new PoiSearch.Query(keyword, "", "全国"); query.setPageSize(10); query.setPageNum(0); try { PoiSearch search = new PoiSearch(requireContext(), query); search.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() { @Override public void onPoiSearched(PoiResult result, int rCode) { requireActivity().runOnUiThread(() -> { if (rCode == 1000 && result != null && !result.getPois().isEmpty()) { PoiItem item = result.getPois().get(0); LatLonPoint point = item.getLatLonPoint(); // ✅ 使用地图当前中心作为起 LatLng center = aMap.getCameraPosition().target; Intent intent = new Intent(requireContext(), RoutePlanActivity.class); intent.putExtra(RoutePlanActivity.EXTRA_SOURCE, RoutePlanActivity.SOURCE_FROM_MAP_DIRECT); intent.putExtra("start_lat", center.latitude); intent.putExtra("start_lng", center.longitude); intent.putExtra("target_lat", point.getLatitude()); intent.putExtra("target_lng", point.getLongitude()); intent.putExtra("target_title", item.getTitle()); startActivity(intent); } else { handlePoiSearchError(rCode); } }); } @Override public void onPoiItemSearched(PoiItem item, int rCode) {} }); search.searchPOIAsyn(); } catch (Exception e) { e.printStackTrace(); Toast.makeText(requireContext(), "搜索失败:" + e.getMessage(), Toast.LENGTH_LONG).show(); } }); } return root; } private void handlePoiSearchError(int rCode) { String errorMsg; switch (rCode) { case 1101: errorMsg = "网络连接异常"; break; case 1102: errorMsg = "网络响应超时"; break; case 1103: errorMsg = "解析异常"; break; case 1104: errorMsg = "请求参数非法"; break; case 1200: errorMsg = "API Key 存在"; break; case 1202: errorMsg = "签名验证失败(SHA1/包名匹配)"; break; case 1206: errorMsg = "API Key 权限足(未开通 POI 搜索服务)"; break; default: errorMsg = "未知错误: " + rCode; break; } Toast.makeText(requireContext(), "搜索失败: " + errorMsg, Toast.LENGTH_LONG).show(); } /** * 初始化地图 */ private void initMap() { if (aMap == null) { aMap = mapView.getMap(); UiSettings uiSettings = aMap.getUiSettings(); uiSettings.setZoomControlsEnabled(true); // 显示缩放按钮 uiSettings.setCompassEnabled(true); // 显示指南针 uiSettings.setMyLocationButtonEnabled(false); // 我们自己控制定位行为 } } @Override public void onResume() { super.onResume(); //每次恢复可见时都检查权限状态 mapView.onResume(); // ✅ 直接开启定位图层(信任 MainActivity 的判断) if (aMap != null) { aMap.setMyLocationEnabled(true); // 只第一次进入时移动相机 if (!isFirstLocationSet) { LatLng defaultLoc = new LatLng(39.909186, 116.397411); aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(defaultLoc, 12f)); isFirstLocationSet = true; } } } @Override public void onPause() { super.onPause(); mapView.onPause(); } @Override public void onDestroyView() { super.onDestroyView(); if (mapView != null) { mapView.onDestroy(); } binding = null; } @Override public void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); mapView.onSaveInstanceState(outState); } } RoutePlanActivity代码如下:package com.example.bus; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.activity.OnBackPressedCallback; import com.amap.api.location.AMapLocation; import com.amap.api.location.AMapLocationClient; import com.amap.api.location.AMapLocationClientOption; import com.amap.api.location.AMapLocationListener; import com.amap.api.maps.AMap; import com.amap.api.maps.CameraUpdateFactory; import com.amap.api.maps.MapView; import com.amap.api.maps.model.LatLng; import com.amap.api.maps.model.LatLngBounds; import com.amap.api.maps.model.PolylineOptions; import com.amap.api.services.core.LatLonPoint; import com.amap.api.services.route.BusPath; import com.amap.api.services.route.BusRouteResult; import com.amap.api.services.route.BusStep; import com.amap.api.services.route.RouteSearch; import java.util.ArrayList; import java.util.List; public class RoutePlanActivity extends AppCompatActivity implements RouteSearch.OnRouteSearchListener, AMapLocationListener { // 来源类型常量 public static final String EXTRA_SOURCE = "extra_source"; public static final int SOURCE_FROM_HOME_SEARCH = 1001; public static final int SOURCE_FROM_MAP_DIRECT = 1002; private MapView mapView; private AMap aMap; private RouteSearch routeSearch; private RecyclerView recyclerSteps; private TextView tvRouteInfo; // 持久显示路线信息 private boolean isSearching = false; private int sourceType = -1; // 定位相关 private AMapLocationClient locationClient; private LatLonPoint currentLocation; // 存储定位到的“我的位置” private LatLonPoint targetPoint; // 存储目标(终) // 新增:防止重复发起搜索 private boolean hasStartedSearch = false; // 🔥 控制只发起一次搜索 // 新增:用于管理返回键行为 private OnBackPressedCallback onBackPressedCallback; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_route_plan); // 获取来源 sourceType = getIntent().getIntExtra(EXTRA_SOURCE, -1); // 获取目标位置 double targetLat = getIntent().getDoubleExtra("target_lat", 0); double targetLng = getIntent().getDoubleExtra("target_lng", 0); if (targetLat == 0 || targetLng == 0) { Toast.makeText(this, "目标位置无效", Toast.LENGTH_SHORT).show(); finish(); return; } targetPoint = new LatLonPoint(targetLat, targetLng); // 初始化视图 mapView = findViewById(R.id.map_view); recyclerSteps = findViewById(R.id.recycler_steps); tvRouteInfo = findViewById(R.id.tv_route_info); // 显示路线信息(持续) mapView.onCreate(savedInstanceState); if (aMap == null) { aMap = mapView.getMap(); } try { routeSearch = new RouteSearch(this); routeSearch.setRouteSearchListener(this); } catch (Exception e) { Log.e("RoutePlan", "RouteSearch 初始化失败", e); tvRouteInfo.setText("路线服务初始化失败"); finish(); return; } if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle("公交路线规划"); } // 初始化定位 initLocation(); // 如果来自 MapFragment,直接发起搜索(需要等定位) if (sourceType == SOURCE_FROM_MAP_DIRECT) { startRouteSearch(); // 🔥 提前发起搜索,等待定位 } // 🔥 替换 onBackPressed:注册 OnBackPressedCallback onBackPressedCallback = new OnBackPressedCallback(true) { @Override public void handleOnBackPressed() { if (sourceType == SOURCE_FROM_MAP_DIRECT) { Intent intent = new Intent(RoutePlanActivity.this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.putExtra("open_tab", "map"); startActivity(intent); finish(); } else { setEnabled(false); getOnBackPressedDispatcher().onBackPressed(); setEnabled(true); } } }; getOnBackPressedDispatcher().addCallback(this, onBackPressedCallback); } /** * 初始化定位客户端 */ private void initLocation() { try { locationClient = new AMapLocationClient(this); AMapLocationClientOption option = new AMapLocationClientOption(); option.setOnceLocation(true); option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy); option.setMockEnable(false); locationClient.setLocationOption(option); locationClient.setLocationListener(this); locationClient.startLocation(); tvRouteInfo.setText("正在获取您的位置..."); } catch (Exception e) { Log.e("RoutePlan", "定位初始化失败", e); tvRouteInfo.setText("定位服务启动失败"); finish(); } } /** * 发起公交路线搜索(增加防重发机制) */ private void startRouteSearch() { if (isSearching || hasStartedSearch) return; // 🔥 防止重复搜索 hasStartedSearch = true; // ✅ 标记已发起搜索 LatLonPoint start = null; // 来自 SearchResultActivity:使用定位结果作为起 if (sourceType == SOURCE_FROM_HOME_SEARCH) { if (currentLocation == null) { tvRouteInfo.setText("无法获取您的位置,请稍后重试"); finish(); return; } start = currentLocation; } // 来自 MapFragment:使用传入的起坐标 else if (sourceType == SOURCE_FROM_MAP_DIRECT) { double startLat = getIntent().getDoubleExtra("start_lat", 0); double startLng = getIntent().getDoubleExtra("start_lng", 0); if (startLat == 0 || startLng == 0) { tvRouteInfo.setText("请输入有效的起"); finish(); return; } start = new LatLonPoint(startLat, startLng); } else { tvRouteInfo.setText("未知操作来源"); finish(); return; } // 构建查询 RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(start, targetPoint); RouteSearch.BusRouteQuery query = new RouteSearch.BusRouteQuery(fromAndTo, RouteSearch.BUS_DEFAULT, "全国", 0); isSearching = true; tvRouteInfo.setText("正在规划路线..."); routeSearch.calculateBusRouteAsyn(query); } @Override public void onLocationChanged(AMapLocation loc) { if (loc != null && loc.getErrorCode() == 0) { currentLocation = new LatLonPoint(loc.getLatitude(), loc.getLongitude()); Log.d("RoutePlan", "✅ 定位成功: " + loc.getLatitude() + "," + loc.getLongitude()); // 只有来自 SearchResultActivity 才在此处开始搜索 if (sourceType == SOURCE_FROM_HOME_SEARCH && !hasStartedSearch) { startRouteSearch(); } // 🔥 其他情况(如 MapDirect)已经搜过或需要定位数据,无需处理 } else { Log.e("RoutePlan", "❌ 定位失败: " + (loc != null ? loc.getErrorInfo() : "null")); tvRouteInfo.setText("定位失败,请检查权限"); Toast.makeText(this, "无法获取位置", Toast.LENGTH_LONG).show(); finish(); } } @Override public void onBusRouteSearched(BusRouteResult result, int rCode) { isSearching = false; if (rCode != 1000 || result == null || result.getPaths().isEmpty()) { tvRouteInfo.setText("未找到公交路线"); return; } BusPath bestPath = result.getPaths().get(0); // 默认最优路线 drawRouteOnMap(bestPath); StepAdapter adapter = new StepAdapter(bestPath.getSteps()); recyclerSteps.setLayoutManager(new LinearLayoutManager(this)); recyclerSteps.setAdapter(adapter); // ✅ 手动计算总时间和换乘次数 long totalDuration = 0; int busRideCount = 0; for (BusStep step : bestPath.getSteps()) { // 公交段 if (step.getBusLine() != null && step.getBusLine().getDuration() > 0) { totalDuration += step.getBusLine().getDuration(); busRideCount++; } // 步行段 else if (step.getWalk() != null) { totalDuration += step.getWalk().getDuration(); } } int transferNum = Math.max(0, busRideCount - 1); // 显示路线概要信息 String info = String.format("⏱️ %d分钟 | 💰 ¥%.2f | 🚌 %d次换乘", totalDuration / 60, bestPath.getCost(), transferNum); tvRouteInfo.setText(info); } /** * 绘制路线 */ private void drawRouteOnMap(BusPath path) { aMap.clear(); List<LatLng> allPoints = new ArrayList<>(); for (BusStep step : path.getSteps()) { // 公交段 if (step.getBusLine() != null && step.getBusLine().getPolyline() != null) { for (LatLonPoint point : step.getBusLine().getPolyline()) { allPoints.add(new LatLng(point.getLatitude(), point.getLongitude())); } } // 步行段 else if (step.getWalk() != null && step.getWalk().getPolyline() != null) { for (LatLonPoint point : step.getWalk().getPolyline()) { allPoints.add(new LatLng(point.getLatitude(), point.getLongitude())); } } // 出入口 fallback else { if (step.getEntrance() != null && step.getEntrance().getLatLonPoint() != null) { LatLonPoint p = step.getEntrance().getLatLonPoint(); allPoints.add(new LatLng(p.getLatitude(), p.getLongitude())); } if (step.getExit() != null && step.getExit().getLatLonPoint() != null) { LatLonPoint p = step.getExit().getLatLonPoint(); allPoints.add(new LatLng(p.getLatitude(), p.getLongitude())); } } } if (!allPoints.isEmpty()) { PolylineOptions options = new PolylineOptions() .addAll(allPoints) .color(0xFF4A90E2) .width(12f); aMap.addPolyline(options); // 聚焦整条路线 LatLngBounds.Builder builder = new LatLngBounds.Builder(); for (LatLng point : allPoints) { builder.include(point); } aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 100)); } else { tvRouteInfo.setText("路线数据为空"); } } @Override public boolean onSupportNavigateUp() { getOnBackPressedDispatcher().onBackPressed(); return true; } // 以下回调处理 @Override public void onDriveRouteSearched(com.amap.api.services.route.DriveRouteResult r, int c) {} @Override public void onWalkRouteSearched(com.amap.api.services.route.WalkRouteResult r, int c) {} @Override public void onRideRouteSearched(com.amap.api.services.route.RideRouteResult r, int c) {} // 生命周期方法 @Override protected void onResume() { super.onResume(); mapView.onResume(); } @Override protected void onPause() { super.onPause(); mapView.onPause(); } @Override protected void onDestroy() { super.onDestroy(); mapView.onDestroy(); if (routeSearch != null) { routeSearch.setRouteSearchListener(null); } if (locationClient != null) { locationClient.onDestroy(); } } @Override protected void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); mapView.onSaveInstanceState(outState); } } 如果MapFragment有问题,请你进行最小量的修改,跟刚刚一样保证原有功能框架变,以免造成过多的报错
11-18
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值