access variables of outer class in Java

ⅰ亾dé卋堺 提交于 2019-11-29 03:27:27

If the dialog variable is a field of the outer class, you can use this prefixed with the outer class name (a qualified this):

send.setOnClickListener(new View.OnClickListener() 
{
    public void onClick(View v) {
       ProgressDialog dlg = OuterClass.this.dialog;
       .......
    }
});

Alternatively, if the dialiog variable is a local variable it needs to be marked as final:

final ProgressDialog dialog = new ProgressDialog(this);
.....
send.setOnClickListener(new View.OnClickListener() 
{
    public void onClick(View v) {
       // The dialog variable is in scope here ...
       dialog.someMethod();
    }
});

Make the outer local variable (dialog) final so you can refer to it from the inner class.

If it's a local variable (like the signature suggests), it needs to be final for the inner class to be able to access it. If it's a member variable, the visibility modifier needs to be default (no modifier) or higher (protected or public). With private -modifier, it still works, but you might get a warning (depending on your compiler-settings):

Read access to enclosing field SomeClass.someField is emulated by a synthetic accessor method

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