如何将MapsActivity插入片段容器?

时间:2016-06-01 23:14:15

标签: android android-fragments

我在默认的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);
}

这是导航抽屉的主要活动

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

我可以设法使第二个代码与除了Maps之外的其他片段一起使用。 可能有什么不对?

2 个答案:

答案 0 :(得分:1)

我不确定这是否是正确的方法,因为文档说明只使用布局中的<fragment>标记,但您可以尝试这样做。

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

如果您愿意,还可以使用newInstance(GoogleMapOptions options)方法为地图提供选项。

答案 1 :(得分:1)

如果您想从Activity中控制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();