Home > front end >  How to use custom listener without new?
How to use custom listener without new?

Time:07-30

I want to pass some signal to activity from my custom view. I use some code from the web, but most of them new a view to override some functions. I already have a view in my activity, so I findViewById it, but don't know why it's not work.

This is my view code

public class MapView extends View {

public interface MyCustomObjectListener {
    public void onObjectReady(String title);
    public void onDataLoaded();
}

private MyCustomObjectListener listener;

public void setCustomObjectListener(MyCustomObjectListener listener) {
    this.listener = listener;
}
//... some code

and this is my activity code

        View mapview = findViewById(R.id.mapview); // <---- error
        mapview.setCustomObjectListener(new MapView.MyCustomObjectListener(){
            @Override
            public void onObjectReady(String title) {
            }
            @Override
            public void onDataLoaded() {
            }
        });

        MapView mpview = new MapView(this,null);
        mpview.setCustomObjectListener(new MapView.MyCustomObjectListener(){
            @Override
            public void onObjectReady(String title) {
            }
            @Override
            public void onDataLoaded() {
            }
        });

the error message

error: cannot find symbol
        mapview.setCustomObjectListener(new MapView.MyCustomObjectListener(){
               ^
  symbol:   method setCustomObjectListener(<anonymous MyCustomObjectListener>)
  location: variable mapview of type View

CodePudding user response:

You are using View object for MapView

View mapview = findViewById(R.id.mapview); 

Change this to :

MapView mapview = findViewById(R.id.mapview);
  • Related