Best practice to pass Context to non-activity classes?

前端 未结 3 1482
暖寄归人
暖寄归人 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:06

    You can do that using ContextWrapper, as described here.

    For example:

    public class MyContextWrapper extends ContextWrapper {
    
        public MyContextWrapper(Context base) {
          super(base);
       }
    
        public void makeMyAppAwesome(){
            makeBaconAndEggsWithMeltedCheese(this);
        }
    }
    

    And call the non activity class like this from an Activity

    new MyContextWrapper(this);
    

提交回复
热议问题