Akeshwar Jha
Akeshwar Jha

Reputation: 4576

How to 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 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?

Upvotes: 4

Views: 4097

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075209

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);
    }
}

Upvotes: 9

Related Questions