gpt4 book ai didi

java - 使用 FragmentManager 和 FragmentTransaction 将 Map Fragment 动态添加到 Activity 中

转载 作者:行者123 更新时间:2023-12-01 08:47:13 25 4
gpt4 key购买 nike

我一直在搜索很多有关将 map fragment 添加到 Activity 中并执行 fragment 事务以添加和删除 map fragment 的信息,就像普通 fragment 一样。我在 stackoverflow 上找到了很多旧帖子,但大多数人都使用 getMap() 方法来获取googleMap 对象,但当前版本的 map 没有 getMap() 方法,但它有 getMapAsync() 所以我找到的解决方案不是我正在寻找的解决方案。我发现也有人用这个GoogleMap map=((MapFragment)getActivity().getFragmentManager().findFragmentById(R.id.map)).getMap() 但这里 getMap() 在当前版本的 map 中也未定义。那么任何人都可以给我一个正确的指导来实现。这是代码,我想如何实现这一目标:

public class MainActivity extends Fragment{
GoogleMap map;
MapView v;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.activity_main,container,false);
return view;
}

}

其中activity_main是包含Map fragment 的布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.kamaloli.mapdemo.MainActivity">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_activity_map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.kamaloli.mapdemo.MainActivity" />
</RelativeLayout>

所以我想做的就是像普通 fragment 一样使用 fragment 事务将此 fragment 添加到另一个 Activity 中。

最佳答案

将此 map fragment 添加到 fragment (MapFragment)布局文件中:

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

公开声明mapview和googlemap:

private MapView mapView;
private GoogleMap googleMap;

将以下代码添加到 onViewCreated() 中:

mapView = (MapView) view.findViewById(R.id.map);
mapView.onCreate(savedInstanceState);
mapView.onResume();
mapView.getMapAsync(this);

在您的 fragment 中实现 OnMapReadyCallback 并添加此方法:

@Override
public void onMapReady(GoogleMap map) {
googleMap = map;
}

在activity_main.xml中添加一个容器:

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

// Add all activity contents here

<FrameLayout/>

将此容器替换为 MapFragment:

FragmentManager fm = getFragmentManager():
fm.beginTransaction.replace(R.id.container, new MapFragment()).commit();

希望这有帮助。

关于java - 使用 FragmentManager 和 FragmentTransaction 将 Map Fragment 动态添加到 Activity 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42604861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com