我在默认的MapsActivity上有以下代码:

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;

@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);
}


这在导航抽屉MainActivity上

MapsActivity fragment = new MapsActivity();
    FragmentTransaction fragmentTransaction =
            getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.fragment_container, fragment);
    fragmentTransaction.commit();


我可以设法使第二个代码与除Maps之外的其他片段一起工作。
有什么事吗

最佳答案

如果要从“活动”中控制SupportMapFragment,则the answer from cricket_007将正常工作。

如果需要自定义功能,并且希望将其保留在Fragment中,则可以创建扩展SupportMapFragment的Fragment,例如:

public class MyCustomMapFragment extends SupportMapFragment
                          implements OnMapReadyCallback {

    private GoogleMap mMap;

    public MyCustomMapFragment () {
    }

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

        setUpMapIfNeeded();
    }

    private void setUpMapIfNeeded() {

        if (mMap == null) {
            getMapAsync(this);
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {

        mMap = googleMap;
        mMap.setMyLocationEnabled(true);
        mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
        mMap.getUiSettings().setMapToolbarEnabled(false);
    }

}


然后,您可以使用FragmentTransaction将容器替换为自定义的SupportMapFragment:

MyCustomMapFragment fragment = new MyCustomMapFragment();
FragmentTransaction fragmentTransaction =
        getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();

关于android - 如何将MapsActivity插入 fragment 容器?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37580267/

10-12 02:36