如何将MainActivity设为Android启动页并实现按钮跳转地图功能
Hey there! Let's break down why your map isn't working when you click that button in MainActivity, and fix it properly.
The Core Problem
When you call setContentView(R.layout.activity_maps) directly in the button click, you're just swapping the UI layout—but you're never actually initializing the MapsActivity itself. None of its lifecycle methods (like onCreate()) run, so the SupportMapFragment never gets set up, onMapReady() never fires, and all your location logic stays dormant. That's why your Toasts and logs from onMapReady() never show up.
Solution 1: Launch MapsActivity as a Separate Activity (Simplest Fix)
Since you already have a fully functional MapsActivity that works when it's the launch screen, the easiest fix is to just start it with an Intent instead of swapping layouts.
Updated MainActivity.java
public class MainActivity extends AppCompatActivity { Button getPopLocationButton; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.map_screen); getPopLocationButton = findViewById(R.id.buttonPopLocation); getPopLocationButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Replace setContentView with an Intent to launch MapsActivity Intent mapIntent = new Intent(MainActivity.this, MapsActivity.class); startActivity(mapIntent); } }); } }
Double-Check Your AndroidManifest.xml
Make sure MainActivity is set as the launch activity, and MapsActivity is registered properly:
<application ...> <!-- MainActivity as the launch screen --> <activity android:name=".MainActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- Register MapsActivity --> <activity android:name=".MapsActivity" android:exported="false" /> <!-- Don't forget your Google Maps API key --> <meta-data android:name="com.google.android.geo.API_KEY" android:value="YOUR_API_KEY_HERE" /> </application>
Solution 2: Embed the Map as a Fragment (No Screen Transition)
If you want to show the map directly in MainActivity without opening a new screen, convert your map logic into a Fragment and load it dynamically.
Step 1: Create MapFragment.java (Replace MapsActivity)
public class MapFragment extends SupportMapFragment implements OnMapReadyCallback, LocationListener { private GoogleMap mMap; private LocationManager locationManager; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getMapAsync(this); } @Override public void onMapReady(GoogleMap googleMap) { Toast.makeText(getContext(), "inside onMapReady()", Toast.LENGTH_SHORT).show(); Log.i("hurray:", "inside onMapReady()"); mMap = googleMap; requestLocationPermission(); } private void requestLocationPermission() { Context context = getContext(); if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1); } else { setupLocationUpdates(); } } private void setupLocationUpdates() { Context context = getContext(); if (context == null) return; locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); try { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); } catch (SecurityException e) { e.printStackTrace(); } } @Override public void onLocationChanged(@NonNull Location location) { if (location != null && mMap != null) { Toast.makeText(getContext(), "Location is not null", Toast.LENGTH_SHORT).show(); LatLng userLatLng = new LatLng(location.getLatitude(), location.getLongitude()); MarkerOptions marker = new MarkerOptions() .position(userLatLng) .title("Current position") .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)); mMap.addMarker(marker); mMap.moveCamera(CameraUpdateFactory.newLatLng(userLatLng)); mMap.animateCamera(CameraUpdateFactory.zoomTo(10)); Toast.makeText(getContext(), location.toString(), Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getContext(), "location is null !", Toast.LENGTH_SHORT).show(); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == 1 && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { setupLocationUpdates(); } } }
Step 2: Update activity_main.xml (Add Fragment Container)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:id="@+id/buttonPopLocation" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show Map" /> <!-- Container for the map fragment (hidden by default) --> <FrameLayout android:id="@+id/map_container" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:visibility="gone" /> </LinearLayout>
Step 3: Update MainActivity to Load the Fragment
public class MainActivity extends AppCompatActivity { Button getPopLocationButton; FrameLayout mapContainer; boolean isMapLoaded = false; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.map_screen); getPopLocationButton = findViewById(R.id.buttonPopLocation); mapContainer = findViewById(R.id.map_container); getPopLocationButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mapContainer.setVisibility(View.VISIBLE); // Load the fragment only once if (!isMapLoaded) { getSupportFragmentManager().beginTransaction() .add(R.id.map_container, new MapFragment()) .commit(); isMapLoaded = true; } } }); } }
Critical Reminders
Don't forget to declare these permissions in your AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.INTERNET" />
内容的提问来源于stack exchange,提问作者Ubaid Khan

