Static member views in activity - Android

后端 未结 4 664
栀梦
栀梦 2020-12-20 05:49

In each of the activities in my application, all the views (grids/lists/buttons... lots of them) are declared as static members of the activity. Is this good practice or is

4条回答
  •  天命终不由人
    2020-12-20 06:09

    You should not qualify your view variables in your Activity class as static, since a static variable is for the class rather than for your Activity instance:

    Public MyActivity extends Activity {
        private static final string TAG = MyActivity.class.getSimpleName(); // This is a good candidate for `static`.
        private static Switch myFirstSwitch; // This is a bad candidate for `static`
        private Switch mySecondSwitch; // This is good, and can be accessed by onCreate(), onResume(), etc.
        // …
    }
    

    If you have not encountered issues so far while using myFirstSwitch, it is because in practice Android instantiates a single MyActivity instance when parsing file AndroidManifest.xml. So at the application level there is no significant difference between using static variables and not using them, although internally static variables have to be handled differently.

    However, in theory, you could instantiate MyActivity multiple times in your code by yourself. For example, for some reasons or just for testing purposes, you might write somewhere MyActivity testActivity = new MyActivity(); In this case you might be in trouble using the static myFirstSwitch variable.

提交回复
热议问题