【问题标题】:Can we write MyLocationListener outside the xxxActivity class?我们可以在 xxxActivity 类之外写 MyLocationListener 吗?
【发布时间】:2012-01-09 20:42:12
【问题描述】:

我可以在 MainActivity 类之外编写 MyLocationListener 吗?如下例

MainActivity.class

public class MainActivity extends Activity{

    @Override
    ..onCreate(){
    .
    .
    loclis = new MyLocationListener(this); // Can i use it this way? 
    //if so, where is the best place to declare this line. 

    }
}

MyLocationListener.class

public class MyLocationListener implement LocationListener{
..
.//Constructor of MyLocationListener
}

感谢您的帮助

【问题讨论】:

    标签: android location android-location locationlistener


    【解决方案1】:

    是的,您可以将独立类声明为位置侦听器。但是,如果您这样做了,您可能希望有一种机制,允许您的侦听器在位置更改时回调您的活动(否则您的活动将永远不会知道您获得了位置更新):

    public class MyLocationListener implements LocationListner{
    
       private SomeInterface owner;
    
       public MyLocationListener(SomeInterface owner){
           this.owner = owner;
    } 
    
    }
    

    那么您的活动可能如下所示:

    public class MainActivity extends Activity implements SomeInterface{
    
        private LocationListner locListener;
        public void onCreate(Bundle savedInstanceState){
            locListener = new MyLocationListener(this);
        }
    
    }
    

    【讨论】:

    • 顺便说一句,如果我想在 MainActivity 的 R.layout.main 中设置文本值。我是否需要像这样实现构造函数: public MyLocationListener(Activity activity,SomeInterface owner){ this.owner = owner;
    猜你喜欢
    • 1970-01-01
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2017-12-27
    • 2013-04-25
    • 1970-01-01
    相关资源
    最近更新 更多