【问题标题】:Toast current location in Navigation Drawer Activity action bar在导航抽屉活动操作栏中吐司当前位置
【发布时间】:2015-04-20 08:39:27
【问题描述】:

所以我有一个Navigation Drawer Activity (a non activity class)。有一个按钮(在操作栏上)应该 Toast 当前位置在 LatitudeLongitude 但我无法让 getsystemservice()Navigation Drawer Activity 中工作。

下面是代码。

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_SERVICE);,它一直告诉我该方法没有解决,而它在 Main.java 活动中完全没问题。

如何获得在抽屉活动中工作的纬度和经度? 有没有更简单的编码方法?

谢谢。

【问题讨论】:

  • 是的。如果它是你的非活动类,那么你应该提供一个内容引用来调用它。喜欢context.getSystemService(Context.LOCATION_SERVICE);

标签: android android-activity android-actionbar


【解决方案1】:

使用 getActivity()

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

【讨论】:

    【解决方案2】:

    当你在android中使用fragment时,你应该使用方法getActivity()来获取上下文(所有fragment都依赖于一个activity),所以正如上面评论中所说,你必须使用方法getActivity()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多