为什么在 Picasso.with(context) 中,Picasso 要求提供 context 参数?

3
Picasso.with(context) 中...
public static Picasso with(Context context) {
  if (singleton == null) {
    synchronized (Picasso.class) {
      if (singleton == null) {
        singleton = new Builder(context).build();
      }
    }
  }
  return singleton;
}

而 Builder(Context context) 就像这样

/** Start building a new {@link Picasso} instance. */
public Builder(Context context) {
  if (context == null) {
    throw new IllegalArgumentException("Context must not be null.");
  }
  this.context = context.getApplicationContext();
}

为什么 Picasso 在每次都执行 setting context = context.getApplicationContext( ) 的情况下还要请求上下文呢?
2个回答

4
创建 Picasso 实例后,您无需传递上下文。使用构建器即可。
    // create Picasso.Builder object
    Picasso.Builder picassoBuilder = new Picasso.Builder(context);

    // Picasso.Builder creates the Picasso object to do the actual requests
    Picasso picasso = picassoBuilder.build(); 

    // instead of Picasso.with(Context context) you directly use this new custom Picasso object

picasso  
    .load(UsageExampleListViewAdapter.eatFoodyImages[0])
    .into(imageView1);

欲了解更多信息,请点击以下链接:

https://futurestud.io/blog/picasso-customizing-picasso-with-picasso-builder

该链接提供了有关定制Picasso的详细信息。请注意保留HTML标记。

3
您已经发布了您的答案 -
public Builder(Context context) {
  if (context == null) {
    throw new IllegalArgumentException("Context must not be null.");
  }
  this.context = context.getApplicationContext();
}

Picasso是一种库而不是应用程序。如果在创建Picasso实例时没有传递context,那么你认为它将如何获取application context? 为了使其正常工作,它需要context,并且这必须由使用该库的应用程序提供。


6
它还可以通过切换到应用程序上下文来防止泄漏“Activity”(如果您传递的是这个)。 - Jake Wharton
非常感谢 @JakeWharton 提供的清晰解释! - Suraj Kumar Sau

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接