Android Toast导航抽屉活动操作栏中的当前位置
所以我有一个Android Toast导航抽屉活动操作栏中的当前位置,android,android-activity,android-actionbar,Android,Android Activity,Android Actionbar,所以我有一个导航抽屉活动(一个非活动类)。有一个按钮(在操作栏上)应该Toast在纬度和经度中的当前位置,但我无法使getsystemservice()在导航抽屉活动中工作 下面是代码 public class NavigationDrawerFragment extends Fragment { public boolean onOptionsItemSelected(MenuItem item) { if (mDrawerToggle.onOptionsItemSel
导航抽屉活动(一个非活动类)
。有一个按钮(在操作栏上)应该Toast
在纬度和经度中的当前位置,但我无法使getsystemservice()
在导航抽屉活动中工作
下面是代码
public class NavigationDrawerFragment extends Fragment {
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (item.getItemId() == R.id.current_location) {
//TODO FInd a way to receive location info
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
if (location != null){
}
String Text = "Current Location: \n" +
"Latitude: " + location.getLatitude() + "\n" +
"Longitude: " + location.getLongitude();
Toast.makeText(getActivity(), Text, Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
}
因此,在getSystemService(Context.LOCATION\u服务)代码>它一直告诉我,该方法在Main.java活动中完全正常,但没有解析
我如何获得在抽屉中工作的经度和纬度?
有没有更简单的编码方法
谢谢。使用getActivity()
LocationManager locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
当您在android中使用片段时,您应该使用方法getActivity()
来获取上下文(所有片段都取决于一个活动),因此正如上面的评论中所述,您必须使用方法getActivity()
是的。如果它是ur非活动类,那么您应该提供一个内容引用来调用它。比如context.getSystemService(context.LOCATION\u服务)代码>