如何引用正确声明匿名类的对象?

And*_*ett 2 java android anonymous-class

我正在为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;
            });
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望获得对菜单按钮的引用,并将其用于我的onTouch方法中的内容(与我认为的问题无关).我知道我可以调用类的方法(例如getApplication())但我特别想要在匿名OnTouchListener中声明对象的引用.

正如你所看到的,我找到了一个解决方案!MenuButton self = this; 线.

有没有一种正确的方法可以做到这一点,还是我的奇怪解决方案唯一的方法呢?

A--*_*--C 5

@Override
public boolean onTouch(View v, MotionEvent event) {
    MenuButton button = MenuButton.this;
});
Run Code Online (Sandbox Code Playgroud)

当在匿名内部类中时,this引用该匿名类实例,因此您必须通过显式指定外部类实例MenuButton.this.