使用在运行时调用的抽象方法的值

时间:2015-01-14 10:15:27

标签: java android abstract-class android-location abstract-methods

我正在尝试使用here中的MyLocation类。在下面的代码中,我需要在实例化MyLocation的类中的任何位置访问变量currentLat和currentLon。我不知道如何访问currentLatcurrentLon

的值

LocationResult locationResult = new LocationResult(){ @Override public void gotLocation(Location location){ currentLat = location.getLatitude(); currentLon = location.getLongitude(); }; } MyLocation myLocation = new MyLocation(); myLocation.getLocation(this, locationResult);

假设我想要

Double x =currentLoc;

我该怎么做?任何帮助将不胜感激

2 个答案:

答案 0 :(得分:0)

而不是匿名类使用你自己的扩展/ implments LocationResult类/接口并添加像这样的getter

    class MyLocationResult extends/implments LocationResult{
    double currentLat;
    double currentLon;

    @Override 
    public void gotLocation(Location location){ 
        currentLat = location.getLatitude(); 
        currentLon = location.getLongitude(); 
    };
    public double getCurrentLat(){
       return currentLat;
    }
    public double getCurrentLon (){
       return currentLon ;
    }
}

然后你可以写

MyLocationResult locationResult = new MyLocationResult();
MyLocation myLocation = new MyLocation(); 
myLocation.getLocation(this, locationResult);

无论什么时候需要currentLat或currentLon,你都可以写

locationResult.getCurrentLat();

答案 1 :(得分:0)

您可以为变量使用static修饰符并全局定义它们。

public static double currentLat; // defined globally...
public static double currentLon;

LocationResult locationResult = new LocationResult(){
   @Override
      public void  gotLocation(Location location){
      currentLat =location.getLatitude(); // assuming getLatitude() returns double or int
      currentLon = location.getLongitude();
    };
}
MyLocation myLocation = new MyLocation();
myLocation.getLocation(this, locationResult);

现在你可以在任何地方访问它们

double x =currentLon;
double y =currentLat;