Search code examples
androidgoogle-mapsandroid-tabhost

Android Studio - How to set a tab content from another activity?


im creating an app with AS and i need to show a Google Map in the third tab of my TabHost. I've read a lot of questions and tutorials and they usually use ActivityGroup(which is deprecated). I cannot put the Google maps code inside my MainActivity.java because I've already exteneded from others:

public class MainActivity extends BaseActivity implements View.OnClickListener{

so how i can solve this problem? I've also read about Fragments if ActivityGroup is deprecated but will this work if I'm using a TabHost?

Thanks in advance!

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    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));
}

Solution

  • The method I have experience with is to use a FragmentTabHost and add the MapFragment to that. If you're declaring the FragmentTabHost in MainActivity, you may need to change Activity to a FragmentActivity. I personally was unable to find an alternative way. But you should be able to change your classes to inherit from FragmentActivity without too much trouble.

    Alternatively, you can stick to using views and add a MapView instead of using SupportMapFragment, but SupportMapFragment will give you more out of the box.