[英]How do I register for an event on an object without the need for an anonymous class?
[英]How do I reference the object an anonymous class is declared in properly?
我正在为Java中的View分配一个OnClick监听器,如下所示:
public class MenuButton extends Fragment {
MenuButton self = this;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
MenuButton button = self;
});
}
}
}
我希望获得对菜单按钮的引用,并将其用于我的onTouch方法中的内容(与我认为的问题无关)。 我知道我可以调用类的方法(例如getApplication())但我特别想要在匿名OnTouchListener中声明对象的引用。
正如你所看到的,我找到了一个解决方案! MenuButton self = this; 线。
有没有一种正确的方法可以做到这一点,还是我的奇怪解决方案唯一的方法呢?
@Override
public boolean onTouch(View v, MotionEvent event) {
MenuButton button = MenuButton.this;
});
当在匿名内部类中时, this
引用了该匿名类实例,因此您必须通过MenuButton.this
明确指定外部类实例。
您可以使用MenuButton.this
来引用外部类实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.