美文网首页
2017.6.6 TintContextWrapper cann

2017.6.6 TintContextWrapper cann

作者: jiongge | 来源:发表于2017-06-06 10:49 被阅读76次

问题描述:

如果一个 View 绘制于某个 Activity 的 ContentView 上, 那它的 Context 一定是和这个 Activity 相关联的. 因此我们想在 View 中直接用 Activity 方法时 (最常用的应该就是 Activity.startActivity() 方法了), 不必再向 View 中传递 Activity 对象.
一般在 View 中获取这个 Activity 对象都是简单的用下面代码就可以了:

Activity activity = (Activity) getContext();

但在 View 继承自 AppCompat 系的 View 时 (比如 AppCompatTextView, AppCompatImageView), 下面方法可能会得到下面异常:

  View view1 = ((Activity) view.getContext()).getLayoutInflater().inflate(R.layout.date_dialog, null);
**java.lang.ClassCastException: android.support.v7.widget.TintContextWrapper cannot be cast to ...Activity**

问题解决:
知道原因就简单了. 可以简单的用 ContextWrapper.getBaseContext()
得到这个 Activity. 但其实一层层的从 ContextWrapper 中把 Activity 剥出来更保险:

/**
     * try get host activity from view.
     * views hosted on floating window like dialog and toast will sure return null.
     * @return host activity; or null if not available
     */
    public static Activity getActivityFromView(View view) {
        Context context = view.getContext();
        while (context instanceof ContextWrapper) {
            if (context instanceof Activity) {
                return (Activity) context;
            }
            context = ((ContextWrapper) context).getBaseContext();
        }
        return null;
    }

如上方法可以通用的解决从 View 中获取 Activity 的问题.
事实上, 谷歌 v7 包中的 Android.support.v7.app.MediaRouteButton
就是这么干的.

相关文章

  • 2017.6.6 TintContextWrapper cann

    问题描述: 如果一个 View 绘制于某个 Activity 的 ContentView 上, 那它的 Conte...

  • 从 context 获取Activity

    有这种情形,比如AppCompatTextView中的context是被TintContextWrapper包裹进...

  • 2019-03-28 可可英语听力训练听写:

    I cann't find my glasses and I cann't see anything. Can y...

  • When you cannot lend directly (2

    Facts: Due to the regulatory restriction, the lender cann...

  • 心想事成

    When we are saying this cannot be accomplished, this cann...

  • 2017.6.6

    愿望:今天能看20分钟的书和整理产品库的东西 结果:这样的话星期五我能够去讲,不被罚钱 障碍:效率太低,我可能没有...

  • 2017.6.6

  • 2017.6.6

    张萌 分享第十天 家家有本难念的经,不表现出来不代表不存在。 早上在上班路上,给我老公说,你二哥二嫂啥时候搬走呀,...

  • 2017.6.6

    1.感恩坦坦陈老师让我再次走进课堂做助教,有机会提升自己,谢谢谢谢谢谢! 2.感恩爱人和婆婆,把两个孩子照顾的很好...

  • 2017.6.6

    周期能带来什么 凡事都有它的周期,懂得了,就能带你成长。 人的情绪也是有周期可循,也有高兴的时候和苦恼的时候,学会...

网友评论

      本文标题:2017.6.6 TintContextWrapper cann

      本文链接:https://www.haomeiwen.com/subject/ajjgfxtx.html