Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override a method only if a condition is found to be true?

Tags:

java

android

In my MainActivity class, I want to stop overriding the attachBaseContext method if a 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;
    }

In my view, I have a button in my main activity layout which calls the stopOverriding() method on getting 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 overriding attachBaseContext() method in all my activities. My question is, is it possible that after clicking the button in the Main Activity, I could stop overriding this attachBaseContext() method in all my activities?

like image 659
Akeshwar Jha Avatar asked Oct 23 '25 09:10

Akeshwar Jha


1 Answers

You can't make a runtime decision about whether a method is overridden (without generating classes dynamically, which is complicated [and I have no idea if it's supported in Dalvik]).

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);
    }
}
like image 141
T.J. Crowder Avatar answered Oct 25 '25 22:10

T.J. Crowder