How do I override a method only if a condition is found to be true?… here is a solution to the problem.
How do I override a method only if a condition is found to be true?
In my MainActivity class, I want to stop overriding the attachBaseContext
method if the button is pressed in my View.
Here’s the situation:
public class MainActivity extends AppCompatActivity {
boolean value = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setting content view and stuff
}
the following should be overridden only if value == true.
I can change the value to false by clicking a button in my view.
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(ZeTarget.attachBaseContext(base,this));
}
public void stopOverriding (View view) {
value = false;
}
It seems to me that there is a button in my main activity layout that calls the stopOverriding()
method when clicked:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:onclick="stopOverriding"
android:text="@string/change"/>
I have the same override attachBaseContext()
method in all my activities. My question is, is it possible that after clicking a button in the main activity, I can stop overriding this attachBaseContext()
method in all activities?
Solution
You can’t decide at runtime whether a method is overridden or not (which is complicated if the class isn’t generated dynamically [and I don’t know if Dalvik supports it]).
Just check your condition in the method:
protected void attachBaseContext(Context base) {
if (this.value) {
Your special behavior
super.attachBaseContext(ZeTarget.attachBaseContext(base,this));
} else {
The super's behavior, as though you hadn't overridden the method
super.attachBaseContext(base);
}
}