最佳实践通过上下文非活动课?上下文、活动课

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

所以,我的第一个主要应用是近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);
    }
}
阅读全文

相关推荐

最新文章