片段中的android地图

问题描述 投票:3回答:1

我正在尝试创建一个具有一个活动和多个片段的Android应用程序。每个片段在视图中都会占用整个屏幕,并且在替换事务时它应该切换到另一个片段。

<FrameLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

这是片段的容器。问题是我想要使用的片段是GoogleMap。这是我的地图片段代码:

public class Map extends Fragment{
private final static String TAG = "MAP Fragment";
public GoogleMap googleMap = null;

@Override
public void onCreate(Bundle savedInstanceState) 
{
        super.onCreate(savedInstanceState);
        setUpMapIfNeeded();
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.map_fragment, null);
    return view;
}

private void setUpMapIfNeeded()
{
    if(googleMap == null)
    {
        googleMap = ((MapFragment) getActivity().getFragmentManager().findFragmentById(R.id.map)).getMap();
        if(googleMap != null)
        {
            GoogleMapOptions options = new GoogleMapOptions();
            options.mapType(GoogleMap.MAP_TYPE_NORMAL)
                .camera(new CameraPosition(new LatLng(25f, 47f), 13f, 0f, 0f));
        }
        else
        {
            Log.d(TAG, "googleMap is null !!!!!!!!!!!!!!!");
        }
    }
}

}

它的布局:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/map"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:name="com.google.android.gms.maps.MapFragment"/>

在主要活动中:

@Override
protected void onCreate(Bundle savedInstanceState) 
{
Map test = new Map();
getSupportFragmentManager().beginTransaction()
            .add(R.id.content_frame, test)
            .commit();
}

我得到一个空指针异常:(我相信它找不到R.id.map)

googleMap = ((MapFragment) getActivity().getFragmentManager()
.findFragmentById(R.id.map)).getMap();

如果我不使用“getActivity()”。它说它无法从Fragment转换为MapFragment。

我需要“googleMap”才能在地图上创建标记。

当我创建相同的应用程序但没有片段(我的主要活动显示地图,我没有其他片段)一切正常。

我发现了类似的主题:Google Maps API v2 Custom MapFragment + SimpleFragmenterror using maps in fragment。但是,如果我扩展FragmentActivity或SupportMapFragment,我无法使用事务替换另一个片段。

结论:我希望当一个动作发生时(点击或其他)我只需要替换这样的碎片:

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, newFragment);

我究竟做错了什么?或者我应该采取不同的方法来解决问题?

(P.S.我对android比较新)

android android-fragments google-maps-android-api-2
1个回答
1
投票

问题是我在setUpMapIfNeeded()中调用onCreate()之前尝试更改map元素(视图仅在onCreateView()中膨胀)。

如果我在setUpMapIfNeeded()中移动调用onResume()一切正常,因为然后视图被夸大并且它可以使用地图并修改它。

This is where I found the answer

© www.soinside.com 2019 - 2024. All rights reserved.