![](/img/trans.png)
[英]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.