问题
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