当前位置:  开发笔记 > 编程语言 > 正文

无法在导航抽屉中的Fragment中解析getSystemService

如何解决《无法在导航抽屉中的Fragment中解析getSystemService》经验,为你挑选了1个好方法。

我正在尝试实现一个导航抽屉,它在片段中有一个地图.这是我的代码.

这里是 fragment_map.xml



    
    


然后我在我的网站上调用了FragmentMap ExtractMenu.java

 public void onNavigationDrawerItemSelected(int position) {
        Fragment fragment = null;

        switch (position){
            case 0:
                fragment = new FragmentMap();
                break;
        }

        if (fragment != null){
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
        }
    }

然后在FragmentMap.java下面的代码中添加了缩放,ap到当前位置.

 public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        mMap.setMyLocationEnabled(true); // Identify the current location of the device
        mMap.setOnMyLocationChangeListener(this); // change the place when the device is moving

        Location currentLocation = getMyLocation(); // Calling the getMyLocation method

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



 // Implement getMyLocation

        public Location getMyLocation() {
            LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); // Get location from GPS if it's available
            Location myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            // Location wasn't found, check the next most accurate place for the current location
            if (myLocation == null) {
                Criteria criteria = new Criteria();
                criteria.setAccuracy(Criteria.ACCURACY_COARSE);
                // Finds a provider that matches the criteria
                String provider = lm.getBestProvider(criteria, true);
                // Use the provider to get the last known location
                myLocation = lm.getLastKnownLocation(provider);
            }
            return myLocation;
        }

在这里我无法解决getSystemService任何人都知道为什么?有没有更好的方法来缩放片段中的地图?



1> IntelliJ Ami..:

Fragment中的getActivity()返回Fragment当前与之关联的Activity.

你正在使用Fragment,所以你需要添加getActivity().我希望它能帮到你.

最后,

 LocationManager lm = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);

推荐阅读
135369一生真爱_890
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有