Best practice to pass Context to non-activity classes?

前端 未结 3 1490
暖寄归人
暖寄归人 2020-12-02 07:51

So, my first major application is almost coded and I\'m doing optimizations on my code. The app works fine, but I\'m not sure about my way of passing the context to other cl

3条回答
  •  感动是毒
    2020-12-02 08:17

    You could also create a static instance reference to your MainActivity initialized in the onCreate() method

    public class MainActivity extends AppCompatActivity {
    
        public static MainActivity mMainActivity;
    
        @Override
        private onCreate(Bundle savedInstanceState){
    
        //...
    
        mMainActivity = this;
    
        }
    }
    

    and call the context like this:

    MainActivity.mMainActivity;
    

    or write a method getInstanceOf() if it's clearer and/or you prefer using an accessor

    MainActivity.getInstanceOf();
    

    This strategy might provide you with some flexibility if you decide later that you would like to call an instance method contained in your main activity like so:

    MainActivity.mMainActivity.myInstanceMethod();
    

    Just a suggestion. Criticism is welcome and encouraged.

提交回复
热议问题