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
.......
}
});
Since inner classes are members of the outer class, you can apply any access modifiers like private , protected to your inner class which is not possible in normal classes. Since the nested class is a member of its enclosing outer class, you can use the dot ( . ) notation to access the nested class and its members.
Java inner class is associated with the object of the class and they can access all the variables and methods of the outer class.
In general you use OuterClassName. this to refer to the enclosing instance of the outer class.
The Java language supports five distinct access levels for variables: private, private protected, protected, public, and, if left unspecified, "friendly".
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();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With