【问题标题】:How to use SupportMapFragment inside a Fragment?如何在 Fragment 中使用 SupportMapFragment?
【发布时间】:2014-07-31 05:11:12
【问题描述】:

我知道使用嵌套片段存在问题。但是我的应用程序被设计为在片段上运行,如果我将使用地图活动,我的投射功能将会出错。

我想就如何实现这一目标向您寻求帮助。我一直在互联网上搜索,但找不到最佳解决方案。

我试过这段代码:

private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) myFragmentActivity.getSupportFragmentManager().findFragmentById(R.id.map_con))
                .getMap();
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            mMap.setMyLocationEnabled(true);
        }
    }
}

这会给我重复的错误,因为 R.id.map_con 是我的片段中的片段。

所以我寻找解决方法,这一次,R.id.map_con 是一个框架布局,在运行时我为它创建了 SupportMapFragment。

SupportMapFragment mSupportMapFragment = new SupportMapFragment();
    myFragmentActivity.getSupportFragmentManager().beginTransaction()
            .replace(R.id.map_con, mSupportMapFragment).commit();

虽然这不会在每次关闭和打开片段时给我一个副本。但我的错误是 mSupportMapFragment.getMap 始终为空。我不明白为什么它为空?。

mMap = mSupportMapFragment.newInstance().getMap();
        if (mMap != null){
            Log.e("ReportFragment","mMap is not empty");
        }else{
            Log.e("ReportFragment","mMap is empty");
        }

非常感谢你们提供的任何意见,或者您是否还有其他解决方法但仍在此过程中,即片段内的片段

谢谢

chkm8

【问题讨论】:

    标签: android google-maps supportmapfragment


    【解决方案1】:

    getMap() 已弃用

    Fragment 中的代码应该是这样的:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    
        View v = inflater.inflate(R.layout.fragment_location, container, false);
    
        mMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
        mMapFragment.getMapAsync(this);
    
        return v;   
    }
    

    【讨论】:

    • 这是从十几篇 SO 帖子和网络文章中唯一对我有用的答案。
    • 这对我有用,从技术上讲,是的,getChildFragmentManager() 是正确的答案。谢谢@lpfx。
    • 这个问题的正确答案,请为这个答案投票,以便人们尽早解决问题。
    • 这应该是公认的答案,因为本质上我们是在片段中调用片段,然后应该调用 getChildFragmentManager()
    • 这样在go main fragment to back stack然后pop back map太卡了
    【解决方案2】:

    我碰巧碰上了,在发这个帖子的时候,我找到了我要找的东西。

    我用过这个:

     @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_location, container, false);
        mMapFragment = new SupportMapFragment() {
            @Override
            public void onActivityCreated(Bundle savedInstanceState) {
                super.onActivityCreated(savedInstanceState);
                mMap = mMapFragment.getMap();
                if (mMap != null) {
                    setupMap();
                }
            }
        };
        getChildFragmentManager().beginTransaction().add(R.id.framelayout_location_container, mMapFragment).commit();
    return v;   
    }
    

    感谢Old post

    【讨论】:

    • setupMap()方法的实现是什么?
    • 现在我正在崩溃,消息“java.lang.IllegalArgumentException:实现 IObjectWrapper 的具体类必须为包装对象准确声明 one 的私有字段。最好,这是 ObjectWrapper 类的一个实例。”使用 play-services-location:9.0.2 请帮帮我。
    • 你可以调用 mMapFragment.getMapAsync 和 getMap 他们
    【解决方案3】:

    我已经以给定的方式使用它并且它工作正常。

    它也适用于getChildFragmentManager()

    MapyFragment

    public class MapyFragment extends Fragment implements OnMapReadyCallback {
    
        private Context mContext;
        private SupportMapFragment supportMapFragment;
        private GoogleMap map;
        private MarkerOptions currentPositionMarker = null;
        private Marker currentLocationMarker;
    
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            mContext = getActivity();
            return inflater.inflate(R.layout.fragment_mapy, container, false);
        }
    
        @Override
        public void onActivityCreated(@Nullable Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
    
            mContext = getActivity();
    
            FragmentManager fm = getActivity().getSupportFragmentManager();/// getChildFragmentManager();
            supportMapFragment = (SupportMapFragment) fm.findFragmentById(R.id.map_container);
            if (supportMapFragment == null) {
                supportMapFragment = SupportMapFragment.newInstance();
                fm.beginTransaction().replace(R.id.map_container, supportMapFragment).commit();
            }
            supportMapFragment.getMapAsync(this);
        }
    
        @Override
        public void onMapReady(GoogleMap googleMap) {
            map = googleMap;
            if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                    ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            map.setMyLocationEnabled(true);
            map.animateCamera(CameraUpdateFactory.zoomTo(15));
            /*map.setOnMapLongClickListener(MapyFragment.this);
            map.setOnMapClickListener(MapFragment.this);*/
        }
    
        public void updateCurrentLocationMarker(Location currentLatLng){
    
            if(map != null){
    
                LatLng latLng = new LatLng(currentLatLng.getLatitude(),currentLatLng.getLongitude());
                if(currentPositionMarker == null){
                    currentPositionMarker = new MarkerOptions();
    
                    currentPositionMarker.position(latLng)
                            .title("My Location").
                            icon(BitmapDescriptorFactory.fromResource(R.drawable.start_blue));
                    currentLocationMarker = map.addMarker(currentPositionMarker);
                }
    
                if(currentLocationMarker != null)
                    currentLocationMarker.setPosition(latLng);
    
                ///currentPositionMarker.position(latLng);
                map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
            }
        }
    }
    

    和fragment_mapy.xml

    <?xml version="1.0" encoding="utf-8"?>
    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        android:id="@+id/map_container"
        class="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        map:uiZoomControls="true" />
    

    【讨论】:

      【解决方案4】:

      在 kotlin 中可以这样做:

      class NameFragment: Fragment(){
          // other code ...
          private lateinit var googleMapsFragment: SupportMapFragment
      
          override fun onCreateView(
                  inflater: LayoutInflater, container: ViewGroup?,
                  savedInstanceState: Bundle?
          ): View {
               googleMapsFragment = childFragmentManager.findFragmentById(R.id.map_fragment) as SupportMapFragment
              // other code ...
          }
      }
      

      【讨论】:

        【解决方案5】:

        在 Java 中创建 SupportMapFragment?

        您也可以像这样在 Fragment 中创建 SupportMapFragment。

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
        
            View view = inflater.inflate(R.layout.fragment_maps, parent, false);
            SupportMapFragment supportMapFragment = SupportMapFragment.newInstance();
        
            getChildFragmentManager()
                .beginTransaction()
                .add(R.id.mapContainer, supportMapFragment)
                .commit();
        
            supportMapFragment.getMapAsync(this::onMapReady);
            
            return view;
        }
        

        这是布局R.layout.fragment_maps的代码

        <androidx.coordinatorlayout.widget.CoordinatorLayout 
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <fragment
               android:id="@+id/map"
               android:layout_width="match_parent"
               android:layout_height="match_parent"
            />
            <!-- Other Widgets like FAB, Bottomsheet-->
        </androidx.coordinatorlayout.widget.CoordinatorLayout>
        

        注意:

        在活动中膨胀片段是一种常见的做法。

        • 创建片段的实例
        • 在片段容器中充气

        所以我采用了相同的方法在 Fragment 中扩展 SupportMapFragment。

        【讨论】:

          猜你喜欢
          • 2015-04-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-12-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多