【问题标题】:How to load a Mapfragment after a button click单击按钮后如何加载地图片段
【发布时间】:2014-07-11 08:09:34
【问题描述】:

我有一个 MainActivity 扩展 ActionBarAcitivity 引用 main_screen_layout.xml

它还有一个抽屉和一个操作栏。 我在这个活动中有一个按钮。单击此按钮后,我想加载地图。

对于地图,我有一个包含

的 mapfragment.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment">
</fragment>

和类 Mapfragment.java 扩展 Fragment 引用 mapfragment.xml Mapfragment.java 实现了 onCreateView 方法。

现在我在运行时将此片段添加到 mainactivity。那工作正常。 但是如何从我的活动中操作片段内的地图?

【问题讨论】:

  • 为什么不实现 Mapfragment 并在单击按钮时使其可见/不可见?这样会更容易
  • 但这仍然会加载地图。点击按钮后我想在地图上加载。

标签: android google-maps google-maps-api-3 android-fragments google-maps-android-api-2


【解决方案1】:
  1. 获取附加在活动上的片段
  2. 例如片段frag = getFragmentManager().findFragmentById/Tag(id/tag);
  3. 获取片段的根视图
  4. 例如视图根 = frag.getView();
  5. 找到你的目标视图来操作它,就像在一个活动中一样。
  6. 例如查看目标 = root.findViewById(id);

【讨论】:

  • 我正在使用 SupportFragmentManager。当我尝试从我的活动中检索片段时,我得到 null。
【解决方案2】:

更简单的方法是使用 mapView。

把你的片段 xml 这个:

<com.google.android.gms.maps.MapView
        android:id="@+id/mapId"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
</com.google.android.gms.maps.MapView>

在你的 java 片段类中:

MapView mapView = (MapView) getActivity().findViewById(R.id.mapId); //get view

GoogleMap map = mapView.getMap(); //working with map

mapView.setVisibility(View.GONE); //to make disappear map
mapView.setVisibility(View.VISIBLE); // to make appear map

【讨论】:

  • 更改可见性仍会加载地图。它只是不会显示它。我想在点击按钮后加载地图。
  • 如果你把属性“android:visibility="invisible"”放在你的xml中,地图仍然加载?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多