今天在复习Glide的原理,然后就顺道过了一遍项目中的封装Glide工具类,看到了有个别方法为了不传入context类型的参数进来,直接通过这种方式:
Glide.with(view.context)
而检查了Glide的源码,看到只有以下的方法
Glide.with(Context context);// 绑定Context
Glide.with(Activity activity);// 绑定Activity
Glide.with(FragmentActivity activity);// 绑定FragmentActivity
Glide.with(Fragment fragment);// 绑定Fragment
但是需要注意的是with()方法中传入的实例会决定Glide加载图片的生命周期,如果传入的是Activity、Fragment或者FragmentActivity的实例,
那么当其被销毁时图片加载也会停止,如果传入的是ApplicationContext时只有当应用程序被杀掉的时候图片加载才会停止。
于是就想知道,以上的写法,是否拿到的就是Activity呢?
查了一下:
/**
* Returns the context the view is running in, through which it can
* access the current theme, resources, etc.
*
* @return The view's Context.
*/
@ViewDebug.CapturedViewProperty
public final Context getContext() {
return mContext;
}
public void setContentView(@LayoutRes int layoutResID) {
getWindow().setContentView(layoutResID);
initWindowDecorActionBar();
}
public void setContentView(int layoutResID) {
if (mContentParent == null) {
installDecor(); //首先初始化DecorView
} else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
mContentParent.removeAllViews();
}
//.........
}
View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
boolean ignoreThemeAttr) {
if (name.equals("view")) {
name = attrs.getAttributeValue(null, "class");
}
// Apply a theme wrapper, if allowed and one is specified.
if (!ignoreThemeAttr) {
//这里为View创建了一个ContextThemeWrapper类型的Context
final TypedArray ta = context.obtainStyledAttributes(attrs, ATTRS_THEME);
final int themeResId = ta.getResourceId(0, 0);
if (themeResId != 0) {
context = new ContextThemeWrapper(context, themeResId);
}
ta.recycle();
}
if (name.equals(TAG_1995)) {
// Let's party like it's 1995!
return new BlinkLayout(context, attrs);
}
try {
View view;
if (mFactory2 != null) {
view = mFactory2.onCreateView(parent, name, context, attrs);
} else if (mFactory != null) {
view = mFactory.onCreateView(name, context, attrs);
} else {
view = null;
}
if (view == null && mPrivateFactory != null) {
view = mPrivateFactory.onCreateView(parent, name, context, attrs);
}
if (view == null) {
final Object lastContext = mConstructorArgs[0];
mConstructorArgs[0] = context;
try {
if (-1 == name.indexOf('.')) {
view = onCreateView(parent, name, attrs);
} else {
view = createView(name, null, attrs);
}
} finally {
mConstructorArgs[0] = lastContext;
}
}
return view;
}
}
综上,View中的Context是ContextThemeWrapper类型的。在View被绘制之前的初始化过程中被创建。
这个LayoutInflater的context是PhoneWindow传进去的,而PhoneWindow的context就是Activity的this。