如果条件为真,如何覆盖一个方法?

3
在我的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()方法?


为什么不根据value的值来改变行为呢?if (value){ foo(); }else{ bar(); } - Arc676
@Arc676 你能否进一步说明吗? - Akeshwar Jha
1个回答

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

谢谢,我明白了。所以,根据我想要的行为(覆盖/不覆盖),我将不得不在MainActivity类本身中声明value为true/false。我如何在所有其他活动中使用我设置的这个值?我是否需要在所有其他活动中单独进行声明? - Akeshwar Jha
@Akeshwar:条件可以是该方法可以访问的任何内容。所以,是的,value可以使用,或者它可以检查的任何其他内容也可以。 - T.J. Crowder
我只是在想如何在所有活动中最好地使用value,于是我决定将其存储在我的主活动文件中,然后在所有其他活动中访问该文件。感谢您的答案,解决了我的问题。 - Akeshwar Jha
你应该考虑使用SharedPreferences而不是文件,因为它是存储应用程序键值对的首选方式:http://developer.android.com/training/basics/data-storage/shared-preferences.html - Björn Kechel
感谢您的回复,@bjornson。我现在正在使用SharedPreferences。但是我现在使用它们时遇到了一个新问题。请查看这个链接:http://stackoverflow.com/questions/34664901/can-we-have-a-global-variable-with-respect-to-an-entire-android-application - Akeshwar Jha

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接