Chloe
Chloe

Reputation: 26264

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.

Upvotes: 11

Views: 1827

Answers (3)

skrat
skrat

Reputation: 5562

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?

Upvotes: 13

Bohemian
Bohemian

Reputation: 424983

Just call the method on Adapter directly:

list.setAdapter(new Adapter() {
  public View getView() {
    // ...
    button.setListener(new Listener() {
      public void onClick() {
        remove(item); // <-- this will call Adapter's method of the anonymous class
      }
    );
  }
});

Upvotes: 1

GingerHead
GingerHead

Reputation: 8230

its simple as this: try outer.remove without this class pointer

Upvotes: 0

Related Questions