Android Services设置ProgressBar(进度条的值)

本文介绍Android中的服务组件(MyServices)实现进度更新的功能。通过startService()启动服务,并使用stopService()停止服务。服务内部利用自定义线程(MyThread)更新进度条,进度更新通过Handler发送消息实现。

Services实现效果:



开启服务方法:

startService(intent);

关闭服务方法:

stopService(intent);

服务执行完毕后自动调用onDestroy方法
stopSelf();

//继承Service
package com.example.g160628_android_23_services1;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.IntDef;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.ProgressBar;

/**
 * Created by Administrator on 2017/7/14.
 */

public class MyServices extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("test","onCreate");
    }

    @Override
    public int onStartCommand(Intent intent,int flags, int startId) {
          new MyThread(intent,startId).start();
        Log.i("test","onStartCommand");
        return Service.START_STICKY;
    }

    class MyThread extends Thread{
        private int startId;
        private  Intent intent;

        public MyThread(Intent intent,int startId){
            this.startId=startId;
            this.intent=intent;
        }


        Handler handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                int i=msg.what;
                MainActivity.progressBar.setProgress(i);
            }
        };

        @Override
        public void run() {
            for (int i =1; i <=100 ; i++) {
                handler.sendEmptyMessage(i);
                SystemClock.sleep(200);
                Log.i("test","   "+i);
            }
            //服务执行完毕后自动调用onDestroy方法
            stopSelf(startId);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("test","onDestroy");
    }
}

//主actity
package com.example.g160628_android_23_services1;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {

    private Intent intent;
    public static  ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        intent = new Intent(this,MyServices.class);
    }

    //开始执行
    public void start(View view){
        startService(intent);
    }

    //关闭
    public void stop(View view){
        stopService(intent);
    }
}









是我的疏忽,我没给你提供layout文件。SearchResultActivity代码如下: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.util.Log; import android.widget.Button; 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.TextWatcher; import android.text.Editable; import android.widget.ArrayAdapter; import com.amap.api.services.core.AMapException; import java.util.ArrayList; import java.util.List; 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 boolean isMapInitialized = false; // 地图相关 private MapView mapView; private AMap aMap; private Marker selectedMarker; private static final int LOCATION_PERMISSION_REQUEST_CODE = 1001; // 👇 新增:用于输入提示和城市识别 private Inputtips inputTips; private GeocodeSearch geocodeSearch; // 🔔 新增:用于缓存待处理的第一个 POI private boolean hasPendingSelect = false; private PoiItem pendingFirstItem = null; // ✅ 当前城市,默认 fallback private String currentCity = "全国"; @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); setupSearch(savedInstanceState); // ✅ 初始化 GeocodeSearch try { geocodeSearch = new GeocodeSearch(this); geocodeSearch.setOnGeocodeSearchListener(this); } catch (Exception e) { e.printStackTrace(); } enableMyLocationLayer(); } private void initViews() { searchBtn = findViewById(R.id.search_btn); resultListView = findViewById(R.id.result_list); goToBtn = findViewById(R.id.btn_go_to); goToBtn.setEnabled(false); setupSearchSuggestion(); } /** * 设置搜索输入建议(自动补全) */ 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 ); ((android.widget.AutoCompleteTextView) findViewById(R.id.search_input)) .setAdapter(adapter); } else { ((android.widget.AutoCompleteTextView) findViewById(R.id.search_input)) .setAdapter(null); handleSearchError(rCode); } } }); } catch (AMapException e) { e.printStackTrace(); Toast.makeText(this, "输入提示初始化失败", Toast.LENGTH_SHORT).show(); } android.widget.AutoCompleteTextView inputView = findViewById(R.id.search_input); Handler handler = new Handler(Looper.getMainLooper()); Runnable[] pendingRunnable = {null}; inputView.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) { inputView.setAdapter(null); return; } pendingRunnable[0] = () -> { try { // ✅ 使用动态城市进行提示搜索 inputTips.requestInputtips(s.toString(), currentCity); } catch (AMapException e) { e.printStackTrace(); Toast.makeText(SearchResultActivity.this, "提示请求失败", Toast.LENGTH_SHORT).show(); } }; handler.postDelayed(pendingRunnable[0], 600); } @Override public void afterTextChanged(Editable s) {} }); } private void handleSearchError(int rCode) { String msg; switch (rCode) { case 12: msg = "API Key 错误,请检查 AndroidManifest.xml"; 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 setupMap(Bundle savedInstanceState) { mapView = findViewById(R.id.map_view); mapView.onCreate(savedInstanceState); aMap = mapView.getMap(); if (aMap != null) { initMapSettings(); } else { startWaitingForMap(); } } private void startWaitingForMap() { final Handler handler = new Handler(Looper.getMainLooper()); final Runnable waitTask = new Runnable() { int retryCount = 0; final int maxRetries = 50; @Override public void run() { if (mapView == null) return; aMap = mapView.getMap(); if (aMap != null) { Log.d("SearchResult", "✅ 地图已成功获取!"); initMapSettings(); } else if (retryCount < maxRetries) { retryCount++; Log.d("SearchResult", "⏳ 正在等待地图初始化... 第 " + retryCount + " 次"); handler.postDelayed(this, 200); } else { Log.e("SearchResult", "❌ 地图初始化超时"); Toast.makeText(SearchResultActivity.this, "地图加载超时", Toast.LENGTH_SHORT).show(); } } }; handler.post(waitTask); } private void initMapSettings() { try { 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)); isMapInitialized = true; maybeSelectFirstItem(); } catch (Exception e) { Log.e("SearchResult", "初始化地图失败", e); Toast.makeText(this, "地图设置异常", Toast.LENGTH_SHORT).show(); } } private void enableMyLocationLayer() { if (aMap == null) return; if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { try { MyLocationStyle myLocationStyle = new MyLocationStyle(); myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE); aMap.setMyLocationStyle(myLocationStyle); aMap.setMyLocationEnabled(true); Toast.makeText(this, "已开启定位(单次居中)", Toast.LENGTH_SHORT).show(); // ✅ 请求一次定位以获取城市 requestCityFromLocationOnce(); } catch (Exception e) { e.printStackTrace(); } } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE); } } /** * 请求一次定位并解析城市 */ private void requestCityFromLocationOnce() { try { com.amap.api.location.AMapLocationClient locationClient = new com.amap.api.location.AMapLocationClient(this); com.amap.api.location.AMapLocationClientOption option = new com.amap.api.location.AMapLocationClientOption(); option.setLocationMode(com.amap.api.location.AMapLocationClientOption.AMapLocationMode.Battery_Saving); option.setOnceLocation(true); locationClient.setLocationOption(option); locationClient.setLocationListener(location -> { if (location != null && location.getErrorCode() == 0) { double lat = location.getLatitude(); double lon = location.getLongitude(); LatLonPoint point = new LatLonPoint(lat, lon); RegeocodeQuery query = new RegeocodeQuery(point, 200, GeocodeSearch.AMAP); try { geocodeSearch.getFromLocationAsyn(query); } catch (Exception e) { e.printStackTrace(); currentCity = "全国"; } } else { currentCity = "全国"; } locationClient.stopLocation(); locationClient.onDestroy(); }); locationClient.startLocation(); } catch (SecurityException e) { currentCity = "全国"; } catch (Exception e) { e.printStackTrace(); currentCity = "全国"; } } @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) { if (aMap != null) { MyLocationStyle myLocationStyle = new MyLocationStyle(); myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE); aMap.setMyLocationStyle(myLocationStyle); aMap.setMyLocationEnabled(true); Toast.makeText(this, "已成功开启定位功能", Toast.LENGTH_SHORT).show(); // ✅ 权限通过后立即尝试获取城市 requestCityFromLocationOnce(); } } else { boolean hasCoarse = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED; if (hasCoarse) { Toast.makeText(this, "建议开启精确位置以获得更准确定位", Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, "定位权限被拒绝,部分功能受限", Toast.LENGTH_LONG).show(); } currentCity = "全国"; } } } private void setupSearch(Bundle savedInstanceState) { android.widget.AutoCompleteTextView inputView = findViewById(R.id.search_input); if (savedInstanceState == null) { String keyword = getIntent().getStringExtra("keyword"); if (keyword != null && !keyword.isEmpty()) { inputView.setText(keyword); performSearch(keyword); } } searchBtn.setOnClickListener(v -> { String text = inputView.getText().toString().trim(); if (!text.isEmpty()) { performSearch(text); } else { Toast.makeText(this, "请输入关键词", Toast.LENGTH_SHORT).show(); } }); goToBtn.setOnClickListener(v -> { LatLonPoint targetPoint = null; String title = "选中位置"; if (selectedMarker != null) { LatLng pos = selectedMarker.getPosition(); targetPoint = new LatLonPoint(pos.latitude, pos.longitude); title = selectedMarker.getTitle(); } else if (!poiList.isEmpty()) { PoiItem item = poiList.get(0); targetPoint = item.getLatLonPoint(); title = item.getTitle(); } if (targetPoint == null) { Toast.makeText(this, "暂无目标位置", Toast.LENGTH_SHORT).show(); return; } Intent intent = new Intent(this, RoutePlanActivity.class); intent.putExtra(RoutePlanActivity.EXTRA_SOURCE, RoutePlanActivity.SOURCE_FROM_HOME_SEARCH); intent.putExtra("target_lat", targetPoint.getLatitude()); intent.putExtra("target_lng", targetPoint.getLongitude()); intent.putExtra("target_title", title); startActivity(intent); }); } private void performSearch(String keyword) { // ✅ 使用动态城市 PoiSearch.Query query = isLikelyBusStop(keyword) ? new PoiSearch.Query(keyword, "15", currentCity) : 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) { e.printStackTrace(); Toast.makeText(this, "搜索启动失败", Toast.LENGTH_SHORT).show(); } } private boolean isLikelyBusStop(String keyword) { return keyword.contains("公交") || keyword.contains("地铁") || keyword.contains("BRT") || keyword.endsWith("站") || keyword.endsWith("场"); } @Override public void onPoiSearched(PoiResult result, int rCode) { runOnUiThread(() -> { Log.d("SearchResult", "onPoiSearched called, rCode: " + rCode); if (rCode == 1000 && result != null && result.getPois() != null && !result.getPois().isEmpty()) { List<PoiItem> newPoiList = result.getPois(); poiList.clear(); poiList.addAll(newPoiList); if (adapter == null) { adapter = new ResultAdapter(poiList, item -> { if (selectedMarker != null) { selectedMarker.remove(); selectedMarker = null; } 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(); } hasPendingSelect = true; pendingFirstItem = poiList.get(0); goToBtn.setEnabled(true); if (isMapInitialized) { maybeSelectFirstItem(); } } else { String msg = rCode == 17 ? "高德Key校验失败" : rCode == 33 ? "请求过于频繁,请稍后再试" : "搜索失败,错误码=" + rCode; Toast.makeText(this, msg, Toast.LENGTH_LONG).show(); goToBtn.setEnabled(false); } }); } private void maybeSelectFirstItem() { if (!hasPendingSelect || pendingFirstItem == null || aMap == null) { return; } try { LatLonPoint lp = pendingFirstItem.getLatLonPoint(); LatLng latLng = new LatLng(lp.getLatitude(), lp.getLongitude()); if (selectedMarker != null) { selectedMarker.remove(); selectedMarker = null; } selectedMarker = aMap.addMarker(new MarkerOptions() .position(latLng) .title(pendingFirstItem.getTitle())); aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14f), new AMap.CancelableCallback() { @Override public void onFinish() { goToBtn.setEnabled(true); } @Override public void onCancel() { goToBtn.setEnabled(true); } }); hasPendingSelect = false; pendingFirstItem = null; Log.d("SearchResult", "✅ 成功自动选中第一个搜索结果"); } catch (Exception e) { Log.e("SearchResult", "自动选中第一个 item 失败", e); goToBtn.setEnabled(true); } } @Override public void onPoiItemSearched(PoiItem item, int rCode) {} // ✅ 实现 OnGeocodeSearchListener 接口方法 @Override public void onRegeocodeSearched(RegeocodeResult result, int rCode) { if (rCode == 1000 && result != null && result.getRegeocodeAddress() != null) { String city = result.getRegeocodeAddress().getCity(); if (city != null && !city.isEmpty()) { currentCity = city; } else { currentCity = 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(); if (aMap != null) { aMap.setMyLocationEnabled(false); } if (poiSearch != null) { poiSearch.setOnPoiSearchListener(null); } mapView = null; aMap = null; poiSearch = null; inputTips = null; geocodeSearch = null; } @Override protected void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); mapView.onSaveInstanceState(outState); } @Override public boolean onSupportNavigateUp() { onBackPressed(); return true; } } activity_search_result.xml代码如下:<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/root_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" android:layout_marginTop="?attr/actionBarSize"> <!-- ====== 指南线:用于精确百分比定位 ====== --> <!-- 地图底部 --> <androidx.constraintlayout.widget.Guideline android:id="@+id/guideline_60" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" app:layout_constraintGuide_percent="0.60" /> <!-- 结果列表顶部留白结束位置 --> <androidx.constraintlayout.widget.Guideline android:id="@+id/guideline_65" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" app:layout_constraintGuide_percent="0.65" /> <!-- 按钮顶部位置 --> <androidx.constraintlayout.widget.Guideline android:id="@+id/guideline_90" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" app:layout_constraintGuide_percent="0.90" /> <!-- 🔍 输入框 --> <AutoCompleteTextView android:id="@+id/search_input" android:layout_width="0dp" android:layout_height="wrap_content" android:hint="请输入需要查询的公交线路或站点" android:textColorHint="#777777" android:textColor="@color/black" android:background="@drawable/rounded_edittext" android:minHeight="48dp" android:textSize="14sp" android:padding="12dp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toStartOf="@id/search_btn" app:layout_constraintHorizontal_chainStyle="packed" app:layout_constraintTop_toTopOf="parent" android:layout_marginStart="16dp" android:layout_marginEnd="8dp" /> <!-- 🔎 搜索按钮 --> <Button android:id="@+id/search_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="搜索" app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toEndOf="@id/search_input" app:layout_constraintEnd_toEndOf="parent" android:layout_marginEnd="16dp" /> <!-- 🗺️ 地图视图 --> <com.amap.api.maps.MapView android:id="@+id/map_view" android:layout_width="0dp" android:layout_height="0dp" android:layout_marginTop="20dp" app:layout_constraintTop_toBottomOf="@id/search_input" app:layout_constraintBottom_toTopOf="@id/guideline_60" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" /> <!-- 🔲 固定高度容器:包裹 RecyclerView --> <androidx.constraintlayout.widget.ConstraintLayout android:id="@+id/container_result_list" android:layout_width="0dp" android:layout_height="0dp" app:layout_constraintTop_toTopOf="@id/guideline_65" app:layout_constraintBottom_toTopOf="@id/guideline_90" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" android:layout_marginHorizontal="16dp"> <!-- 🔽 RecyclerView:内部可滚动 --> <androidx.recyclerview.widget.RecyclerView android:id="@+id/result_list" android:layout_width="0dp" android:layout_height="0dp" android:nestedScrollingEnabled="false" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" android:scrollbars="vertical" android:scrollbarSize="6dp" android:scrollbarThumbVertical="@drawable/custom_scrollbar_thumb" android:scrollbarTrackVertical="@drawable/custom_scrollbar_track"/> <!-- 空状态提示 --> <TextView android:id="@+id/empty_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="暂无搜索结果" android:textColorHint="#777777" android:textColor="@color/black" android:visibility="gone" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> <!-- “到这去”按钮 --> <Button android:id="@+id/btn_go_to" android:layout_width="0dp" android:layout_height="wrap_content" android:text="到这去" android:layout_margin="16dp" app:layout_constraintTop_toTopOf="@id/guideline_90" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintBottom_toBottomOf="parent" /> <!-- 🌀 加载进度条 --> <ProgressBar android:id="@+id/progress_bar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:visibility="gone" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" android:elevation="10dp" /> </androidx.constraintlayout.widget.ConstraintLayout> MapFragment代码如下:package com.example.bus.ui.map; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.text.Editable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.ArrayAdapter; import android.widget.Toast; import com.amap.api.services.core.AMapException; import com.amap.api.services.core.LatLonPoint; import com.amap.api.services.geocoder.GeocodeResult; import com.amap.api.services.geocoder.GeocodeSearch; import com.amap.api.services.geocoder.RegeocodeQuery; import com.amap.api.services.geocoder.RegeocodeResult; import androidx.annotation.NonNull; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; // 👉 新增导入:用于动态修改约束 import androidx.constraintlayout.widget.ConstraintSet; import androidx.constraintlayout.widget.ConstraintLayout; // 🔺 新增导入:用于设置 Marker 颜色 import com.amap.api.maps.model.BitmapDescriptorFactory; 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.PoiItem; import com.amap.api.services.poisearch.PoiResult; import com.amap.api.services.poisearch.PoiSearch; import com.amap.api.services.help.Inputtips; import com.amap.api.services.help.Tip; import com.example.bus.R; import com.example.bus.RoutePlanActivity; import com.example.bus.ResultAdapter; import com.example.bus.databinding.FragmentMapBinding; import java.util.ArrayList; import java.util.List; public class MapFragment extends Fragment implements PoiSearch.OnPoiSearchListener, GeocodeSearch.OnGeocodeSearchListener { private FragmentMapBinding binding; private MapView mapView; private AMap aMap; private Inputtips inputTips; // 数据 private List<PoiItem> poiList = new ArrayList<>(); private ResultAdapter adapter; private PoiSearch poiSearch; // 当前阶段:1=选择起点, 2=选择终点 private int selectionStage = 0; // 缓存已选 POI private PoiItem selectedStartPoi = null; private PoiItem selectedEndPoi = null; private Marker startMarker = null; private Marker endMarker = null; // 缓存关键词,用于智能判断 private String lastStartKeyword = ""; private String lastEndKeyword = ""; // ✅ 当前城市(动态获取) private String currentCity = "全国"; // 默认 fallback private static final int LOCATION_PERMISSION_REQUEST_CODE = 1001; // ✅ 标记是否已经居中过“我的位置” private boolean userHasInteracted = false; // ✅ 新增:用于反地理编码 private GeocodeSearch geocodeSearch; @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = FragmentMapBinding.inflate(inflater, container, false); View root = binding.getRoot(); mapView = binding.mapView; mapView.onCreate(savedInstanceState); initViews(); setupMap(savedInstanceState); setupSearchSuggestion(); return root; } private void initViews() { // 初始化 RecyclerView adapter = new ResultAdapter(poiList, this::onPoiItemSelected); binding.resultList.setLayoutManager(new LinearLayoutManager(requireContext())); binding.resultList.setAdapter(adapter); // 设置搜索按钮点击事件 binding.mapSearch.setOnClickListener(v -> performSearch()); // 切换按钮 binding.btnSwitchTarget.setOnClickListener(v -> { if (selectionStage == 1) { showEndpointSelection(binding.mapInput2.getText().toString().trim()); } else if (selectionStage == 2) { showStartpointSelection(binding.mapInput1.getText().toString().trim()); } }); // “到这去” binding.btnGoTo.setOnClickListener(v -> { if (selectedStartPoi != null && selectedEndPoi != null) { Intent intent = new Intent(requireContext(), RoutePlanActivity.class); intent.putExtra(RoutePlanActivity.EXTRA_SOURCE, RoutePlanActivity.SOURCE_FROM_MAP_DIRECT); intent.putExtra("start_lat", selectedStartPoi.getLatLonPoint().getLatitude()); intent.putExtra("start_lng", selectedStartPoi.getLatLonPoint().getLongitude()); intent.putExtra("target_lat", selectedEndPoi.getLatLonPoint().getLatitude()); intent.putExtra("target_lng", selectedEndPoi.getLatLonPoint().getLongitude()); intent.putExtra("target_title", selectedEndPoi.getTitle()); startActivity(intent); } else { Toast.makeText(requireContext(), "请完成起点和终点的选择", Toast.LENGTH_SHORT).show(); } }); } private void performSearch() { String startKeyword = binding.mapInput1.getText().toString().trim(); String endKeyword = binding.mapInput2.getText().toString().trim(); if (startKeyword.isEmpty()) { Toast.makeText(requireContext(), "请输入起点", Toast.LENGTH_SHORT).show(); return; } if (endKeyword.isEmpty()) { Toast.makeText(requireContext(), "请输入终点", Toast.LENGTH_SHORT).show(); return; } // 智能判断:是否可以直接跳转? if (startKeyword.equals(lastStartKeyword) && endKeyword.equals(lastEndKeyword) && selectedStartPoi != null && selectedEndPoi != null) { binding.btnGoTo.performClick(); return; } // 展示 UI binding.containerResultList.setVisibility(View.VISIBLE); binding.buttonGroup.setVisibility(View.VISIBLE); // 👇 使用 ConstraintSet 动态改变约束 ConstraintSet constraintSet = new ConstraintSet(); constraintSet.clone((ConstraintLayout) binding.getRoot()); constraintSet.connect( R.id.map_view, ConstraintSet.BOTTOM, R.id.container_result_list, ConstraintSet.TOP, 0 ); constraintSet.applyTo((ConstraintLayout) binding.getRoot()); // ✅ 标记用户已交互 userHasInteracted = true; // ✅ 隐藏软键盘 View currentFocus = requireActivity().getCurrentFocus(); if (currentFocus != null) { currentFocus.clearFocus(); InputMethodManager imm = (InputMethodManager) requireContext().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(currentFocus.getWindowToken(), 0); } // 后续逻辑不变 if (!startKeyword.equals(lastStartKeyword)) { lastStartKeyword = startKeyword; lastEndKeyword = endKeyword; showStartpointSelection(startKeyword); } else if (!endKeyword.equals(lastEndKeyword)) { lastEndKeyword = endKeyword; showEndpointSelection(endKeyword); } else if (selectedStartPoi == null) { showStartpointSelection(startKeyword); } else { showEndpointSelection(endKeyword); } } private void showStartpointSelection(String keyword) { selectionStage = 1; binding.btnSwitchTarget.setText("前往选择终点"); binding.btnGoTo.setEnabled(false); binding.emptyView.setText("👉 请点击选择起点"); binding.emptyView.setVisibility(View.VISIBLE); binding.resultList.setVisibility(View.GONE); doSearch(keyword); } private void showEndpointSelection(String keyword) { selectionStage = 2; binding.btnSwitchTarget.setText("回到选择起点"); binding.btnGoTo.setEnabled(false); binding.emptyView.setText("👉 请点击选择终点"); binding.emptyView.setVisibility(View.VISIBLE); binding.resultList.setVisibility(View.GONE); doSearch(keyword); } private void doSearch(String keyword) { if (keyword.isEmpty()) return; // ✅ 使用动态获取的城市进行搜索 PoiSearch.Query query = new PoiSearch.Query(keyword, "", currentCity); query.setPageSize(20); query.setPageNum(0); try { poiSearch = new PoiSearch(requireContext(), query); poiSearch.setOnPoiSearchListener(this); poiSearch.searchPOIAsyn(); } catch (Exception e) { e.printStackTrace(); Toast.makeText(requireContext(), "搜索失败", Toast.LENGTH_SHORT).show(); } } /** * 用户点击了某个 POI item */ private void onPoiItemSelected(PoiItem item) { LatLng latLng = new LatLng(item.getLatLonPoint().getLatitude(), item.getLatLonPoint().getLongitude()); if (selectionStage == 1) { // 移除旧的起点标记 if (startMarker != null) { startMarker.remove(); startMarker = null; } // 🔺 设置为绿色 startMarker = aMap.addMarker(new MarkerOptions() .position(latLng) .title("起点:" + item.getTitle()) .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))); selectedStartPoi = item; aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14f)); updateGoToButtonState(); } else if (selectionStage == 2) { // 移除旧的终点标记 if (endMarker != null) { endMarker.remove(); endMarker = null; } // 🔺 设置为红色 endMarker = aMap.addMarker(new MarkerOptions() .position(latLng) .title("终点:" + item.getTitle()) .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))); selectedEndPoi = item; aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14f)); updateGoToButtonState(); } userHasInteracted = true; } /** * 更新“到这去”按钮的状态:只有当起点和终点都已选择时才可点击 */ private void updateGoToButtonState() { binding.btnGoTo.setEnabled(selectedStartPoi != null && selectedEndPoi != null); } @Override public void onPoiSearched(PoiResult result, int rCode) { requireActivity().runOnUiThread(() -> { if (rCode == 1000 && result != null && result.getPois() != null && !result.getPois().isEmpty()) { List<PoiItem> newPoiList = result.getPois(); poiList.clear(); poiList.addAll(newPoiList); if (adapter == null) { adapter = new ResultAdapter(poiList, this::onPoiItemSelected); binding.resultList.setLayoutManager(new LinearLayoutManager(requireContext())); binding.resultList.setAdapter(adapter); } else { adapter.notifyDataSetChanged(); // 滚动到顶部 binding.resultList.scrollToPosition(0); } binding.emptyView.setVisibility(View.GONE); binding.resultList.setVisibility(View.VISIBLE); // ✅ 直接选中第一个 item(真实选中,绿色或红色 Marker) onPoiItemSelected(poiList.get(0)); } else { handleSearchError(rCode); binding.resultList.setVisibility(View.GONE); binding.emptyView.setVisibility(View.VISIBLE); binding.emptyView.setText("⚠️ 未找到相关地点"); } }); } @Override public void onPoiItemSearched(PoiItem item, int rCode) {} private void setupMap(Bundle savedInstanceState) { mapView.onCreate(savedInstanceState); aMap = mapView.getMap(); if (aMap != null) { initMapSettings(); } else { waitAMapReady(); } // ✅ 初始化 GeocodeSearch try { geocodeSearch = new GeocodeSearch(requireContext()); geocodeSearch.setOnGeocodeSearchListener(this); } catch (Exception e) { e.printStackTrace(); } } 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++ < 50) { new Handler(Looper.getMainLooper()).postDelayed(this, 200); } } }, 200); } private void initMapSettings() { UiSettings uiSettings = aMap.getUiSettings(); uiSettings.setZoomControlsEnabled(true); uiSettings.setCompassEnabled(true); uiSettings.setScrollGesturesEnabled(true); uiSettings.setMyLocationButtonEnabled(true); } // ✅ 已移除:maybeSelectFirstItem() private void setupSearchSuggestion() { try { inputTips = new Inputtips(requireContext(), 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<>( requireContext(), android.R.layout.simple_dropdown_item_1line, arr ); requireActivity().runOnUiThread(() -> { if (requireActivity().getCurrentFocus() == binding.mapInput1) { binding.mapInput1.setAdapter(adapter); } else if (requireActivity().getCurrentFocus() == binding.mapInput2) { binding.mapInput2.setAdapter(adapter); } }); } else { requireActivity().runOnUiThread(() -> { binding.mapInput1.setAdapter(null); binding.mapInput2.setAdapter(null); }); handleSearchError(rCode); } } }); } catch (Exception e) { e.printStackTrace(); Toast.makeText(requireContext(), "智能提示初始化失败", Toast.LENGTH_SHORT).show(); } Handler handler = new Handler(Looper.getMainLooper()); Runnable[] pending1 = {null}, pending2 = {null}; binding.mapInput1.addTextChangedListener(new SimpleTextWatcher(s -> { if (pending1[0] != null) handler.removeCallbacks(pending1[0]); if (s.length() == 0) { binding.mapInput1.setAdapter(null); } else { pending1[0] = () -> { try { inputTips.requestInputtips(s.toString(), currentCity); // ✅ 使用当前城市 } catch (AMapException e) { e.printStackTrace(); } }; handler.postDelayed(pending1[0], 600); } })); binding.mapInput2.addTextChangedListener(new SimpleTextWatcher(s -> { if (pending2[0] != null) handler.removeCallbacks(pending2[0]); if (s.length() == 0) { binding.mapInput2.setAdapter(null); } else { pending2[0] = () -> { try { inputTips.requestInputtips(s.toString(), currentCity); // ✅ 使用当前城市 } catch (AMapException e) { e.printStackTrace(); } }; handler.postDelayed(pending2[0], 600); } })); } 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(requireContext(), msg, Toast.LENGTH_SHORT).show(); } @Override public void onResume() { super.onResume(); mapView.onResume(); if (!userHasInteracted) { enableMyLocationLayer(); } } @Override public void onPause() { super.onPause(); mapView.onPause(); } @Override public void onDestroyView() { super.onDestroyView(); mapView.onDestroy(); inputTips = null; geocodeSearch = null; binding = null; } @Override public void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); mapView.onSaveInstanceState(outState); } private void enableMyLocationLayer() { if (aMap == null) return; if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { try { 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()); aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(curLatlng, 16f)); userHasInteracted = true; // ✅ 获取城市信息 LatLonPoint latLonPoint = new LatLonPoint(location.getLatitude(), location.getLongitude()); RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP); try { geocodeSearch.getFromLocationAsyn(query); } catch (Exception e) { e.printStackTrace(); } aMap.setOnMyLocationChangeListener(null); } }; aMap.setOnMyLocationChangeListener(listener); } catch (Exception e) { e.printStackTrace(); } } else { ActivityCompat.requestPermissions(requireActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (aMap != null) { 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()); aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(curLatlng, 16f)); userHasInteracted = true; // ✅ 获取城市信息 LatLonPoint latLonPoint = new LatLonPoint(location.getLatitude(), location.getLongitude()); RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP); try { geocodeSearch.getFromLocationAsyn(query); } catch (Exception e) { e.printStackTrace(); } aMap.setOnMyLocationChangeListener(null); } }; aMap.setOnMyLocationChangeListener(listener); } } } } // ✅ 接收反地理编码结果 @Override public void onRegeocodeSearched(RegeocodeResult result, int rCode) { if (rCode == 1000 && result != null && result.getRegeocodeAddress() != null) { String city = result.getRegeocodeAddress().getCity(); if (city != null && !city.isEmpty()) { currentCity = city; } else { currentCity = result.getRegeocodeAddress().getProvince(); } } else { currentCity = "全国"; } } @Override public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {} private static class SimpleTextWatcher implements android.text.TextWatcher { private final java.util.function.Consumer<CharSequence> onTextChanged; public SimpleTextWatcher(java.util.function.Consumer<CharSequence> onTextChanged) { this.onTextChanged = onTextChanged; } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void afterTextChanged(Editable s) {} @Override public void onTextChanged(CharSequence s, int start, int before, int count) { onTextChanged.accept(s); } } } fragment_map.xml代码如下:<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".ui.map.MapFragment" android:fitsSystemWindows="true" android:layout_marginTop="?attr/actionBarSize"> <!-- 🔹 起点输入框 --> <AutoCompleteTextView android:id="@+id/map_input1" android:layout_width="0dp" android:layout_height="48dp" android:hint="请输入起点" android:textColorHint="#777777" android:textColor="@color/black" android:textSize="14sp" android:background="@drawable/rounded_edittext" android:padding="12dp" android:layout_marginStart="16dp" android:layout_marginEnd="8dp" app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toStartOf="@id/guideline_search" /> <!-- 🔹 终点输入框 --> <AutoCompleteTextView android:id="@+id/map_input2" android:layout_width="0dp" android:layout_height="48dp" android:hint="请输入终点" android:textColorHint="#777777" android:textColor="@color/black" android:textSize="14sp" android:background="@drawable/rounded_edittext" android:padding="12dp" android:layout_marginStart="16dp" android:layout_marginEnd="8dp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toStartOf="@id/guideline_search" app:layout_constraintTop_toBottomOf="@id/map_input1" app:layout_constraintVertical_bias="0" /> <!-- 分割线:75% 处 --> <androidx.constraintlayout.widget.Guideline android:id="@+id/guideline_search" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" app:layout_constraintGuide_percent="0.75" /> <!-- 🔍 搜索按钮 --> <Button android:id="@+id/map_search" android:layout_width="0dp" android:layout_height="0dp" android:text="搜索" android:textSize="16sp" app:layout_constraintStart_toStartOf="@id/guideline_search" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="@id/map_input1" app:layout_constraintBottom_toBottomOf="@id/map_input2" android:layout_marginEnd="16dp" /> <!-- 🗺️ 地图视图:✅ 改为默认到底部 --> <com.amap.api.maps.MapView android:id="@+id/map_view" android:layout_width="0dp" android:layout_height="0dp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@id/map_input2" app:layout_constraintBottom_toBottomOf="parent" android:layout_marginTop="4dp" /> <!-- ====== 指南线:用于精确百分比定位 ====== --> <androidx.constraintlayout.widget.Guideline android:id="@+id/guideline_60" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" app:layout_constraintGuide_percent="0.60" /> <androidx.constraintlayout.widget.Guideline android:id="@+id/guideline_90" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" app:layout_constraintGuide_percent="0.90" /> <!-- 🔲 固定容器包裹列表 --> <androidx.constraintlayout.widget.ConstraintLayout android:id="@+id/container_result_list" android:layout_width="0dp" android:layout_height="0dp" app:layout_constraintTop_toTopOf="@id/guideline_60" app:layout_constraintBottom_toTopOf="@id/guideline_90" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" android:layout_marginHorizontal="16dp" android:visibility="gone"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/result_list" android:layout_width="0dp" android:layout_height="0dp" android:nestedScrollingEnabled="false" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" android:scrollbars="vertical" android:scrollbarThumbVertical="@drawable/custom_scrollbar_thumb" android:scrollbarTrackVertical="@drawable/custom_scrollbar_track" /> <TextView android:id="@+id/empty_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="👉 请点击选择起点" android:textColor="#007AFF" android:textSize="16sp" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> <!-- 按钮组 --> <LinearLayout android:id="@+id/button_group" android:layout_width="0dp" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_margin="16dp" app:layout_constraintTop_toBottomOf="@id/container_result_list" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" android:visibility="gone"> <Button android:id="@+id/btn_switch_target" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:layout_marginEnd="8dp" android:text="前往选择终点" android:textSize="14sp" /> <Button android:id="@+id/btn_go_to" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:layout_marginStart="8dp" android:text="到这去" android:textSize="14sp" android:enabled="false" /> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout> StepAdapter代码如下:package com.example.bus; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.amap.api.services.route.BusStep; import java.util.List; public class StepAdapter extends RecyclerView.Adapter<StepAdapter.StepViewHolder> { private final List<Object> steps; // 🔧 改为 Object 类型以支持多态 public StepAdapter(List<Object> steps) { // 🔧 构造函数参数改为 Object 列表 this.steps = steps; } @NonNull @Override public StepViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(android.R.layout.simple_list_item_2, parent, false); return new StepViewHolder(view); } @Override public void onBindViewHolder(@NonNull StepViewHolder holder, int position) { Object stepObj = steps.get(position); String title = "步行"; String snippet = ""; if (stepObj instanceof BusStep) { BusStep step = (BusStep) stepObj; if (step.getBusLine() != null) { title = step.getBusLine().getBusLineName(); String origin = step.getBusLine().getDepartureBusStation() != null ? step.getBusLine().getDepartureBusStation().getBusStationName() : "未知起点站"; String destination = step.getBusLine().getArrivalBusStation() != null ? step.getBusLine().getArrivalBusStation().getBusStationName() : "未知终点站"; int stationCount = step.getBusLine().getPassStationNum(); int actualRideStops = stationCount + 1; snippet = String.format("从【%s】上车 → 在【%s】下车 (%d站)", origin, destination, actualRideStops); if (step.getExit() != null && step.getExit().getName() != null) { snippet += "\n出站口:" + step.getExit().getName(); } } else if (step.getRailway() != null) { title = "🚇 " + step.getRailway().getTrip(); } else if (step.getWalk() != null) { long distance = (long) step.getWalk().getDistance(); snippet = "步行约 " + distance + "米"; if (step.getEntrance() != null && step.getEntrance().getName() != null) { snippet += " → 前往 " + step.getEntrance().getName(); } } } // 处理虚拟步行段:直接使用预设 description else if (stepObj instanceof RoutePlanActivity.VirtualWalkStep) { RoutePlanActivity.VirtualWalkStep vStep = (RoutePlanActivity.VirtualWalkStep) stepObj; title = "🚶 步行"; // 统一标题 snippet = vStep.description; // ✅ 直接使用 Activity 构造好的描述! } holder.title.setText(title); holder.snippet.setText(snippet); } @Override public int getItemCount() { return steps.size(); } static class StepViewHolder extends RecyclerView.ViewHolder { TextView title, snippet; StepViewHolder(View itemView) { super(itemView); title = itemView.findViewById(android.R.id.text1); snippet = itemView.findViewById(android.R.id.text2); } } } 现在,我需要将SearchResultActivity的逻辑改成MapFragment的搜索逻辑,只不过这边只有一个搜索框用于搜索目的地而已,相当于搜索MapFragment的终点逻辑,而SearchResultActivity当中的其它功能保持不变。也就是说,这边不需要隐藏地图,地图大小一直是按照原来的布局,不需要像MapFragment那么麻烦。请你为我修改SearchResultActivity的代码,为我提供修改好的完整代码,请不要乱加MapFragment中没有的逻辑。
最新发布
11-29
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值