本文共 1021 字,大约阅读时间需要 3 分钟。
public static Activity getActivityFromView(View view) { if (null != view) { Context context = view.getContext(); while (context instanceof ContextWrapper) { if (context instanceof Activity) { return (Activity) context; } context = ((ContextWrapper) context).getBaseContext(); } } return null;}
不一定肯定返回,参考下面代码:
private static boolean shouldWrap(@NonNull Context context) { if (!(context instanceof TintContextWrapper) && !(context.getResources() instanceof TintResources) && !(context.getResources() instanceof VectorEnabledTintResources)) { return VERSION.SDK_INT < 21 || VectorEnabledTintResources.shouldBeUsed(); } else { return false; }}
如果是 5.0 以前,并且没有包装的话,就会直接返回 true;所以也就得出了上面的结论:当运行在 5.0 系统版本以下的手机,并且 Activity
是继承自 AppCompatActivity
的,那么View
的 getConext()
方法,返回的就不是 Activity
而是 TintContextWrapper
。
两种非 Activity
的情况:
自定义 View
的时候传入的不是 Activity
;
使用 AppCompatActivity
并且运行在 5.0 以下的手机上,XML 里面的 View
的 getContext()
方法返回的是 TintContextWrapper
。
参考:
转载地址:http://qycgi.baihongyu.com/