如果发现条件为真,如何覆盖方法?

时间:2016-01-07 10:00:48

标签: java android

在我的MainActivity类中,如果在我的视图中按下按钮,我想停止覆盖attachBaseContext方法。

以下是这种情况:

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

在我看来,我的主要活动布局中有一个按钮,在点击时调用stopOverriding()方法:

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:onclick="stopOverriding"
android:text="@string/change"/>

我在所有活动中都有相同的覆盖attachBaseContext()方法。我的问题是,是否有可能在单击主活动中的按钮后,我可以在所有活动中停止覆盖此attachBaseContext()方法?

1 个答案:

答案 0 :(得分:8)

你无法做出关于方法是否被覆盖的运行时决定(没有动态生成类,这很复杂[我不知道它是否在Dalvik中受支持]。)

只需检查方法中的条件:

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