简体   繁体   English

在Java中访问外部类的变量

[英]access variables of outer class in Java

in Java android application how can i access variables of outer class from the inner anonymous class ? 在Java android应用程序中如何从内部匿名类访问外部类的变量? 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
           .......

        }
    });

If the dialog variable is a field of the outer class, you can use this prefixed with the outer class name ( a qualified this ): 如果对话框变量是外部类的字段,你可以使用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: 或者,如果dialiog变量是局部变量,则需要将其标记为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();
    }
});

使外部局部变量( dialogfinal以便您可以从内部类引用它。

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. 如果它是一个局部变量(如签名所示),则内部类必须是final的才能访问它。 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): 使用private -modifier,它仍然有效,但您可能会收到警告(取决于您的编译器设置):

Read access to enclosing field SomeClass.someField is emulated by a synthetic accessor method 对封闭字段的读访问权SomeClass.someField由合成访问器方法模拟

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM