Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two double nested anonymous inner classes. How to get 1st level anonymous class members?

Inner class is Adapter, inner-inner class is Listener. How to access (obscured) Adapter members/methods from Listener?

list.setAdapter(new Adapter() {
  public View getView() {
    // ...
    button.setListener(new Listener() {
      public void onClick() {
        Adapter.this.remove(item);
      }
    );
  }
});

Normally to access the outer classes members, you just say Outer.this.member, but in this case it gave me the following error (using the actual class):

error: not an enclosing class: ArrayAdapter

So how are you supposed to access an inner class members from an inner-inner class? I don't like multi-level nested anonymous classes, but in this case I'm learning a new API and am not sure of a cleaner way yet. I already have a workaround but wanted to know anyways. remove() isn't really obscured by the inner-inner class so specifying the class isn't really necessary in this case, but wanted to make it clear in the code exactly where this remove() method is. I also wanted to know in case it is obscured. I believe using Outer.$6.remove() would work, but I don't believe it should be that way either.

like image 649
Chloe Avatar asked Mar 31 '12 21:03

Chloe


1 Answers

Assign this to a variable, then access that one of innermost class.

list.setAdapter(new Adapter() {
  public View getView() {
    final Adapter that = this;
    button.setListener(new Listener() {
      public void onClick() {
        that.remove(item);
      }
    );
  }
});

I'm not sure what would be a good naming here. Perhaps adapter?

like image 65
skrat Avatar answered Sep 20 '22 08:09

skrat