Reputation: 151
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
.......
}
});
Upvotes: 15
Views: 21441
Reputation: 16035
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
Upvotes: 1
Reputation: 41757
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();
}
});
Upvotes: 29
Reputation: 6897
Make the outer local variable (dialog
) final
so you can refer to it from the inner class.
Upvotes: 4