0

Я попытался сделать приложение, которое отображает карту с ящиком навигации.Навигация Ящик и Google Maps

Если я запустил MainActivity (активность с навигационным ящиком), который содержит MapsActivity, он отображает только карту и не помещает маркер на карту, но если я запустил только MapsActivity, маркер будет помещен.

Кажется, что если я запустил MainActivity, код внутри MapsActivity не запускается, но почему? Что я могу сделать?

Вот код:

MapsActivity:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { 

private GoogleMap mMap; 
private String providerId = LocationManager.GPS_PROVIDER; 
private Geocoder geo = null; 
private LocationManager locationManager = null; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_maps); 
    // Obtain the SupportMapFragment and get notified when the map is ready to be used. 
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
      .findFragmentById(R.id.map); 
    mapFragment.getMapAsync(this); 
} 

@Override 
public void onMapReady(GoogleMap googleMap) { 
    mMap = googleMap; 

    // Add a marker in Sydney and move the camera 
    LatLng sydney = new LatLng(-34, 151); 
    mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney")); 
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney)); 
} 
// Other methods 
} 

MainActivity:

public class MainActivity extends AppCompatActivity 
    implements NavigationView.OnNavigationItemSelectedListener { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
    fab.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
     } 
    }); 

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
      this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); 
    drawer.setDrawerListener(toggle); 
    toggle.syncState(); 

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); 
    navigationView.setNavigationItemSelectedListener(this); 
} 
//Other methods 
} 

Планировка: activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>  
<android.support.v4.widget.DrawerLayout 
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/drawer_layout" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:fitsSystemWindows="true" tools:openDrawer="start"> 

<include layout="@layout/activity_maps" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" /> 

<include layout="@layout/app_bar_main" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" /> 

<android.support.design.widget.NavigationView 
    android:id="@+id/nav_view" 
    android:layout_width="wrap_content" 
    android:layout_height="match_parent" 
    android:layout_gravity="start" 
    android:fitsSystemWindows="true" 
    app:headerLayout="@layout/nav_header_main" 
    app:menu="@menu/activity_main_drawer" /> 

</android.support.v4.widget.DrawerLayout> 

Планировка: activity_maps.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent"> 

<fragment xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:id="@+id/map" 
    tools:context=".MapsFragment" 
    android:name="com.google.android.gms.maps.SupportMapFragment" 
    tools:layout="@layout/activity_maps" /> 

</RelativeLayout> 

ответ

0

Вы не можете сделать Activity такие как MapActivity в другой деятельности, таких MainActivity. Вместо этого следует использовать MapFragment.

Здесь code, что вы можете посмотреть. Также вы можете попробовать project на моем github, это не mapFragment в Navigation Draw, но может дать вам представление о том, как работает MapFragment.

Пример кода для MapFragment:

public class MapFragment extends Fragment { 

    private SupportMapFragment mMapView; 

    public static MapFragment newInstance(String param1, String param2) { 
     MapFragment fragment = new MapFragment(); 
     return fragment; 
    } 

    MapView mapView; 
    GoogleMap map; 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View v = inflater.inflate(R.layout.fragment_map, container, false); 
     // Gets the MapView from the XML layout and creates it 

     MapsInitializer.initialize(getActivity()); 


     switch (GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity())) { 
      case ConnectionResult.SUCCESS: 
       Toast.makeText(getActivity(), "SUCCESS", Toast.LENGTH_SHORT).show(); 
       mapView = (MapView) v.findViewById(R.id.map); 
       mapView.onCreate(savedInstanceState); 
       // Gets to GoogleMap from the MapView and does initialization stuff 
       if (mapView != null) { 
        map = mapView.getMap(); 
        map.getUiSettings().setMyLocationButtonEnabled(false); 
        map.setMyLocationEnabled(true); 
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10); 
        map.animateCamera(cameraUpdate); 
       } 
       break; 
      case ConnectionResult.SERVICE_MISSING: 
       Toast.makeText(getActivity(), "SERVICE MISSING", Toast.LENGTH_SHORT).show(); 
       break; 
      case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED: 
       Toast.makeText(getActivity(), "UPDATE REQUIRED", Toast.LENGTH_SHORT).show(); 
       break; 
      default: 
       Toast.makeText(getActivity(), GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity()), Toast.LENGTH_SHORT).show(); 
     } 

     // Updates the location and zoom of the MapView 

     LatLng sydney = new LatLng(-33.867, 151.206); 

     map.setMyLocationEnabled(true); 
     map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 13)); 

     map.addMarker(new MarkerOptions() 
       .title("Sydney") 
       .snippet("The most populous city in Australia.") 
       .position(sydney)); 

     return v; 
    } 

    @Override 
    public void onResume() { 
     mapView.onResume(); 
     super.onResume(); 
    } 

    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     mapView.onDestroy(); 
    } 

    @Override 
    public void onLowMemory() { 
     super.onLowMemory(); 
     mapView.onLowMemory(); 
    } 
} 

И это расположение:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
       android:layout_width="match_parent" 
       android:layout_height="match_parent"> 

    <com.google.android.gms.maps.MapView 
     android:id="@+id/map" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:name="com.bojie.materialtest.fragments.UpcomingFragment"/> 

</RelativeLayout> 
+0

ли эта помощь для вас? Если да, примите, спасибо – bjiang

Смежные вопросы