access variables of outer class in Java

女生的网名这么多〃 提交于 2019-11-27 22:08:07

问题


in Java android application how can i access variables of outer class from the inner anonymous class ? Example:

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

           //here i'd like to do something with **dialog** variable
           .......

        }
    });

回答1:


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();
    }
});



回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/9545076/access-variables-of-outer-class-in-java

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