I have an activity which instantiate a class with an interface. How I can get the android context within MyClass with only the reference to the interface?
public class TestActivity extends Activity implements MyInterface {
@Override
public void onCreate(final Bundle savedInstanceState) {
final MyClass myClass = new MyClass(this);
}
@Override
public void onChange() {
}
}
public interface MyInterface {
void onChange();
}
public class MyClass {
public MyClass(MyInterface myInterface) {
// how to get context from myInterface ???
}
}
public class MyClass {
public MyClass(MyInterface myInterface) {
// Get Context
Context context = null;
if (myInterface instanceOf Context)
context = (Context)myInterface;
}
}
If your Activity (which extends Context) is implementing MyInterface and you pass that to MyClass, you just need to cast it to the appropriate type.
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