gpt4 book ai didi

java - 无法解析抽屉导航中 fragment 中的 getSystemService

转载 作者:行者123 更新时间:2023-12-02 14:14:10 25 4
gpt4 key购买 nike

我正在尝试实现一个抽屉导航,其中有一个 fragment 中的 map 。这是我的代码。

这是fragment_map.xml

<FrameLayout 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" tools:context="com.myayubo.FragmentMap">

<!-- TODO: Update blank fragment layout -->
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/btnCity"
/>

</FrameLayout>

然后我在 ExtractMenu.java

中调用 FragmentMap
 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有人知道为什么吗?有没有更好的方法来缩放 fragment 中的 map ?

最佳答案

getActivity() in a Fragment returns the Activity the Fragment is currently associated with.

您使用的是Fragment,所以您需要添加getActivity()。希望对您有帮助。

最后

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

关于java - 无法解析抽屉导航中 fragment 中的 getSystemService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34525632/

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