有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将数据从一个片段传递到另一个片段

我有一个名为PlacesFragment的片段,它有一个按钮,链接到另一个名为RoutePlanerFragment的片段,该片段有一个谷歌地图和一个可选择位置的微调器。当我点击PlacesFragment上的按钮时,我想让路线自动显示在地图上,并且需要从微调器中进行选择

下面是PlacesFragment按钮的代码

Button btnToRoute = (Button) rootView.findViewById(R.id.btnToRoute);
    btnToRoute.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View rootView){
            RoutePlanerFragment routePlanerFragment = new RoutePlanerFragment();
            FragmentManager manager = getFragmentManager();
            manager.beginTransaction().replace(R.id.content, routePlanerFragment, routePlanerFragment.getTag()).commit();

这是我的RoutePlanerFragment的地图和旋转器部分

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.fragment_route_planer, container, false);

    String[] values =
            {"Route berechnen", "Campus Heilbronn Sontheim", "Campus Schwäbisch Hall", "Campus Künzelsau", "Bildungscampus Nord"};
    Spinner spinner = (Spinner) rootView.findViewById(R.id.routeSpinner);
    final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), 安卓.R.layout.simple_spinner_item, values);
    adapter.setDropDownViewResource(安卓.R.layout.simple_dropdown_item_1line);
    spinner.setAdapter(adapter);

    if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return rootView;
    }

    mLocationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
    lastKnownLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    if(lastKnownLocation == null) {
        lastKnownLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    }

    mapView = (MapView) rootView.findViewById(R.id.routePlanerMapView);
    mapView.onCreate(savedInstanceState);
    mapView.onResume(); // needed to get the map to display immediately mMapView.
    mapView.getMapAsync(new OnMapReadyCallback() {
        @Override
        public void onMapReady (GoogleMap mMap){
            googleMap = mMap;
            mMap.getUiSettings().setMyLocationButtonEnabled(true);

            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lastKnownLocation.getLatitude(),lastKnownLocation.getLongitude()), 15));
            mMap.addMarker(new MarkerOptions().position(new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude())).title("Du bist hier!").snippet("Text"));
        }
    });

    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 100, new LocationListener() {
        @Override
        public void onLocationChanged(final Location location) {
            lastKnownLocation = location;
            googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(),location.getLongitude()), 15));
            googleMap.addMarker(new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude())).title("Du bist hier!").snippet("Text"));
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {

        }
    });

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
          @Override
          public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

              LatLng destination = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());

              switch (adapterView.getSelectedItem().toString()) {
                  case "Campus Heilbronn Sontheim":
                      destination = new LatLng(49.122123, 9.211115);
                      break;
                  case "Campus Schwäbisch Hall":
                      destination = new LatLng(49.112536,9.743618);
                      break;
                  case "Campus Künzelsau":
                      destination = new LatLng(49.275552, 9.712164);
                      break;
                  case "Bildungscampus Nord":
                      destination = new LatLng(49.147784, 9.217433);
                      break;
                  default: return;
              }

              final LatLng origin = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());

              GoogleDirection.withServerKey("AIzaSyD89DmgdibFa3PzNFfGkfB6S7c428Gvo9c")
                      .from(origin)
                      .to(destination)
                      .language(Language.GERMAN)
                      .execute(new DirectionCallback() {
                          @Override
                          public void onDirectionSuccess(Direction direction, String rawBody) {
                              if(direction.isOK()) {

                                  googleMap.clear();

                                  googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lastKnownLocation.getLatitude(),lastKnownLocation.getLongitude()), 15));
                                  googleMap.addMarker(new MarkerOptions().position(new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude())).title("Du bist hier!").snippet("Text"));

                                  Route route = direction.getRouteList().get(0);
                                  Leg leg = route.getLegList().get(0);

                                  String wayPointHtml = "";
                                  for (Step step : leg.getStepList()) {
                                      Log.d("BESCHREIBUNG", step.getHtmlInstruction().toString());
                                      wayPointHtml += step.getHtmlInstruction().toString() + "<br/><br/>";
                                  }

                                  WebView webView = (WebView) rootView.findViewById(R.id.routeWebView);
                                  webView.loadData(wayPointHtml, "text/html", "utf-8");

                                  Info distanceInfo = leg.getDistance();
                                  Info durationInfo = leg.getDuration();

                                  TextView routeInfo = (TextView) rootView.findViewById(R.id.routeInfo);
                                  routeInfo.setText("Entfernung: " + distanceInfo.getText() + "Dauer: " + durationInfo.getText());

                                  ArrayList<LatLng> directionPositionList = leg.getDirectionPoint();

                                  PolylineOptions polylineOptions = DirectionConverter.createPolyline(getContext(), directionPositionList, 5, Color.RED);
                                  googleMap.addPolyline(polylineOptions);


                              } else {
                              }
                          }

                          @Override
                          public void onDirectionFailure(Throwable t) {

                          }
                      });
          }

          @Override
          public void onNothingSelected(AdapterView<?> adapterView) {

          }
      }
    );

    return rootView;
}

显示在片段上的值将被放置。xml存储在DummContent中。爪哇

这是你放置的碎片。xml

<ScrollView xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
xmlns:tools="http://schemas.安卓.com/tools"
安卓:layout_width="match_parent"
安卓:layout_height="wrap_content"
tools:context="com.example.ensartok.rossappensar.PlacesFragment">

<LinearLayout
    安卓:layout_width="match_parent"
    安卓:layout_height="match_parent"
    安卓:orientation="vertical">


    <com.google.安卓.gms.maps.MapView
        安卓:id="@+id/mapView"
        安卓:layout_width="match_parent"
        安卓:layout_height="417dp" />

    <TextView
        安卓:id="@+id/name"
        安卓:layout_width="match_parent"
        安卓:layout_height="match_parent"
        安卓:text="Campus Sontheim"
        安卓:textSize="14sp" />

    <TextView
        安卓:id="@+id/street"
        安卓:layout_width="match_parent"
        安卓:layout_height="match_parent"
        安卓:text="Max-Planck-Straße 39"
        安卓:textSize="14sp" />

    <TextView
        安卓:id="@+id/zipplace"
        安卓:layout_width="match_parent"
        安卓:layout_height="match_parent"
        安卓:text="74081 Heilbronn"
        安卓:textSize="14sp" />

    <Button
        安卓:layout_width="match_parent"
        安卓:layout_height="38dp"
        安卓:text="Route berechnen"
        安卓:textSize="14sp" />


</LinearLayout>

这就是DummyContent中包含值的部分。爪哇

public static final Map<String, DummyItem> ITEM_MAP = new HashMap<String, DummyItem>();

static {
    DummyItem standort1 = new DummyItem("1", "HHN Campus Sontheim", "Max-Planck-Straße 39","74081", "Heilbronn","49.122123", "9.211115");
    addItem(standort1);
    DummyItem standort2 = new DummyItem("2", "Campus Schwäbisch Hall", "Ziegeleiweg 4","74523", "Schwäbisch Hall","49.112536", "9.743618");
    addItem(standort2);

    DummyItem standort3 = new DummyItem("3",
            "Reinhold-Würth-Hochschule – Campus Künzelsau",
            "Daimlerstraße 35","74653",
            "Künzelsau",
            "49.275552", "9.712164");
    addItem(standort3);

    DummyItem standort4 = new DummyItem("4",
            "Bildungscampus Nord",
            "Bauteil N / Nr. 12","74076",
            "Heilbronn",
            "49.147784", "9.217433");
    addItem(standort4);
}

很抱歉,这个问题涉及这么多代码,但我想你们需要能够回答我的问题

所以再一次
如果您按下PlacesFragment上的按钮,您将到达RoutePlanerFragment,现在我希望路线自动到达我在PlacesFragment中按下按钮的目的地

希望你们能明白我想解释的


共 (1) 个答案

  1. # 1 楼答案

    您好,据我所知,您可以通过以下方式将数据从一个片段发送到另一个片段

    这将向bundle添加数据

    Bundle bundle = new Bundle();
    bundle.putString("latitude", latitude);
    bundle.putString("longitude", longitude);
    bundle.putString("board_id", board_id);
    Fragment_A fragment = new Fragment_A();
    fragment.setArguments(bundle);
    

    这将从片段_A获取数据

    Bundle bundle=getArguments();
    String latitude =  getArguments().getString("latitude") 
    

    您也可以发送ArrayList