博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
android笔记----通过View获取Activity
阅读量:4284 次
发布时间:2019-05-27

本文共 1021 字,大约阅读时间需要 3 分钟。

通过View获取Activity

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 的情况:

  1. 自定义 View 的时候传入的不是 Activity

  2. 使用 AppCompatActivity 并且运行在 5.0 以下的手机上,XML 里面的 View 的 getContext() 方法返回的是 TintContextWrapper

 

 

参考:

转载地址:http://qycgi.baihongyu.com/

你可能感兴趣的文章
hdu-4704 sum(费马小定理)
查看>>
poj-3641 Pseudoprime numbers(费马小定理)
查看>>
poj-1845 Sumdiv && nyoj - 928 小M的因子和
查看>>
hdu-4549 M斐波那契数列 && nyoj - 1000
查看>>
CodeForces 416B
查看>>
LIGHTOJ 1005(组合数学)
查看>>
poj-2231(Moo Volume) 递推
查看>>
LIGHTOJ 1027(概率 - 期望)
查看>>
LIGHTOJ 1044(动态规划)
查看>>
nyoj-37 回文字符串
查看>>
nyist -- 组队赛(一)
查看>>
nyist -- 组队赛(二)
查看>>
nyoj-Color the necklace(Ploya定理 + 欧拉函数 + 扩展欧几里得(求逆元))
查看>>
hdu-1576(A/B)
查看>>
poj-1284(Primitive Roots)(欧拉函数运用)
查看>>
二叉树的操作(二叉树的创建、先序遍历--->先根、中序遍历---->先左、后续遍历--->后根)
查看>>
zoj-What day is that day?
查看>>
nyist---组队赛(三)
查看>>
C语言位运算符
查看>>
hdu-1565(方格取数(1))---状态压缩
查看>>