【问题标题】:Using value of abstract method called at runtime使用运行时调用的抽象方法的值
【发布时间】:2015-01-14 10:15:27
【问题描述】:

我正在尝试使用来自 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;

我如何得到它?任何帮助将不胜感激

【问题讨论】:

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


    【解决方案1】:

    使用您自己的扩展/实现 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();
    

    【讨论】:

    • 它返回 0.0 我也尝试了 setter 但没有帮助。在 MYLocationResult 值的 gotLocation 方法内部显示,但在其外部它的任何地方都是 0.0
    • 你只能在之前调用 gotLocation() 时调用 getCurrentLat,所以如果你需要 getCurrentLat 但尚未设置,你将拥有 0.0
    【解决方案2】:

    您可以对变量使用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;
    

    【讨论】:

    • 我得到 0.0 但里面的 LocationResult 值不是 0
    • 您确定该值不是0.0 吗?尝试在此行之后记录值currentLat =location.getLatitude(); 放入此行,然后尝试! Log.e("method1 returns",""+location.getLatitude());
    猜你喜欢
    • 2021-10-13
    • 2012-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多