最佳实践通过上下文非活动课? [英] Best practice to pass Context to non-activity classes?

查看:126
本文介绍了最佳实践通过上下文非活动课?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我的第一个主要应用是近codeD和我做优化我的code。该应用程序工作正常,但我不知道我的传递上下文给其他类的方法。我不想做了错误的方式。我偶然发现了文章和问题在这里对#1上下文,哪个是正确的方式将它传递给非活动课。我读的文件为好,但作为一个芬兰人,使复杂的高科技说话更难理解。

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 classes. I don't want to do it the wrong way. I stumbled upon articles and questions here in Stackoverflow about contexts and which is the right way to pass it to non-activity classes. I read the documentation as well, but being a Finn makes complicated tech speak even harder to understand.

所以,一个简​​单的问题。我是通过我的主要活动的情况下,以其他(辅助)班正确的方法是什么?如果没有,我在这里可以阅读更多关于更好的做法是在这些情况下。

So, a simple question. Is my way of passing my main activity's context to other (helper) classes correct? If not, where can I read more about better practice on these situations.

例如: MainActivity.java

For example: MainActivity.java

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle sis){
        super(sis);
        new Helper(MyActivity.this).makeMyAppAwesome();
    }
}

Helper.java

Helper.java

public class Helper {
    Context context;
    Helper(Context ctx){
        this.context = ctx;
    }

    public void makeMyAppAwesome(){
        makeBaconAndEggsWithMeltedCheese(context);
    }
}

这样行吗?这将是很好,如果有人可以提供一个易于阅读的文章有关于这个问题的例子。

Is this OK? It would be nice if someone could provide an easy to read article with examples on this subject.

推荐答案

您可以做,使用 ContextWrapper 这里描述。

例如:

public class MyContextWrapper extends ContextWrapper {

    public MyContextWrapper(Context base) {
      super(base);
   }

    public void makeMyAppAwesome(){
        makeBaconAndEggsWithMeltedCheese(this);
    }
}

这篇关于最佳实践通过上下文非活动课?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆