How does finish() work in OnClick event?

杀马特。学长 韩版系。学妹 提交于 2019-12-05 15:13:38

When you've created an OnClickListener as an anonymous class, the this keyword refers to that listener instance rather than the enclosing class. You could use YourActivityClassName.this instead. You could also just omit the this, and since OnClickListener doesn't have a finish() method so the Activity one will be used.

Onik

In the first case this refers to the Activity instance. In the second case you have an anonymous inner class instantiated with new View.OnClickListener() whose this refers to the instance of the class. Each anonymous inner class has an implicit reference to the outer class it's been instantiated in. That reference is implicitly used when calling finish(), i.e. OuterClassName.this.finish().

How is it working in the second snippet?

The compiler is responsible for passing a reference to the outer class instance into the inner class. It modifies each of the inner class' constructors by adding the reference to the outer class instance as a constructor parameter.


Reference: Core Java Volume I - Fundamentals, 9th Edition, Chapter 6.4: Inner Classes, page 309


As @Gabe Sechan pointed out, in order to refer to the outer class within the anonymous inner class use OuterClassName.this. Reference: How do you get a reference to the enclosing class from an anonymous inner class in Java?.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!