在Fragment布局中使用MapView(Android Maps API V2)无法显示。

8
我正在使用viewpager在2个action bar选项卡之间滑动(使用eclipse向导进行此类导航)。我正在使用android maps v2 api。
我想在其中一个选项卡中放置mapview、button和textview(我猜想不可能使用mapfragment)。
我从xml中填充片段的布局,如下所示:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.first_tab_fragment, container, false);
    }
}

我的 first_tab_fragment.xml:

<?xml version="1.0" encoding="utf-8"?>

  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
   android:layout_height="match_parent" >


<com.google.android.gms.maps.MapView
    android:id="@+id/mapview"
    android:layout_width="100dip"
    android:layout_height="100dip"
    android:layout_alignParentTop="true"
    android:layout_alignRight="@+id/textView1"
    android:layout_marginRight="15dp" >
</com.google.android.gms.maps.MapView>

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/textView1"
    android:layout_centerHorizontal="true"
    android:text="Button" />

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignRight="@+id/button1"
    android:layout_marginBottom="133dp"
    android:text="TextView" />

地图视图没有显示,只有TextView和按钮。我也没有收到任何错误提示。我是否需要编写一些代码来初始化MapView?

请查看此帖子:https://dev59.com/Nl3Va4cB1Zd3GeqPDsnD - notXX
1个回答

28

我通过在onCreateView中添加以下代码解决了它:

   // Gets the MapView from the XML layout and creates it
    mapView = (MapView) v.findViewById(R.id.mapview);

    mapView.onCreate(savedInstanceState);
    mapView.onResume(); //without this, map showed but was empty 

    // Gets to GoogleMap from the MapView and does initialization stuff
    map = mapView.getMap(); 
    map.getUiSettings().setMyLocationButtonEnabled(false);
    map.setMyLocationEnabled(true);


    // Needs to call MapsInitializer before doing any CameraUpdateFactory calls
    try {
        MapsInitializer.initialize(this.getActivity());
    } catch (GooglePlayServicesNotAvailableException e) {
        e.printStackTrace();
    }


    // Updates the location and zoom of the MapView
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(44.14, 14.2), 10);
    map.animateCamera(cameraUpdate);

3
如果您希望 mapView 正常工作,您可能需要在正确的位置处理所有生命周期方法。您应该在Activity的 onResume()方法中放置 mapView.onResume(),在 onPause() 中放置 mapView.onPause(), 以此类推。 - gfrigon
1
谢谢!这个答案不容易找到 :) - Matan Dahan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接