【问题标题】:MapView (android maps api v2) inside fragment layout doesnt show片段布局内的MapView(android maps api v2)不显示
【发布时间】:2013-01-29 11:43:13
【问题描述】:

我正在使用 viewpager 在 2 个操作栏选项卡之间滑动(使用 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" />

MapView 不显示,只显示文本视图和按钮。我也没有错误。我必须编写一些代码来初始化mapview吗?

【问题讨论】:

标签: java android android-fragments android-viewpager android-maps-v2


【解决方案1】:

我通过将此代码添加到 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);

【讨论】:

  • 如果您希望mapView 正常工作,您可能希望在正确的位置处理所有生命周期方法。你应该把mapView.onResume()放在你Activity的onResume()方法中,把onPause()放在the onPause()中等等。
  • 谢谢!这个答案不容易找到:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-21
  • 2015-02-19
相关资源
最近更新 更多