1

Not sure how to phrase the question to be technically correct, but suppose I have an object (outer) that has a method which takes another object (inner) as a parameter - how can I refer to outer from within inner?

To clarify what I mean, here's an example using an Android EditText and an implementation of TextWatcher:

EditText myEditText = getEditText();

myEditText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        // How can I refer to myEditText here in a more generic way than 
        // using myEditText directly?         
    }
});

In this example I could of course just use myEditText inside the TextWatcher implementation. But what I want to know is if there is a more generic way to get to the "outer" object from the "inner" in this case?

I know that one can use MyClass.this when dealing with anonymous inner classes, but that doesn't work in this case.

Dave Schweisguth
  • 36,475
  • 10
  • 98
  • 121
Magnus
  • 17,157
  • 19
  • 104
  • 189
  • 1
    The `TextWatcher` interface doesn't pass the `View` into its methods like the `OnClickListener` interface, if that's what you're thinking of, so using a direct reference is about as good as you can do, unless you want to create your own class that implements `TextWatcher`, with methods that add a `View` parameter to the interface methods. – Mike M. Apr 16 '16 at 10:31
  • Why don't you want to use `myEditText` within the method? It's not clear what more generic way you want, given that `myEditText` is the only relevant variable here. – Jon Skeet Apr 16 '16 at 10:37
  • @JonSkeet I was thinking of a construction similar to `MyClass.this` but that would work in this scenario. It's not that I don't want to use `myEditText` , just that I was curious if there was some more generic way to do it that I didn't know about, but I guess not. – Magnus Apr 16 '16 at 10:45
  • That doesn't answer why you don't want to use the construction that *will* work, namely just using `myEditText`. – Jon Skeet Apr 16 '16 at 10:45

0 Answers0