美文网首页
从 context 获取Activity

从 context 获取Activity

作者: CODERLIHAO | 来源:发表于2021-03-04 10:15 被阅读0次
  private static Activity findActivity(@NonNull Context context) {
    if (context instanceof Activity) {
      return (Activity) context;
    } else if (context instanceof ContextWrapper) {
      return findActivity(((ContextWrapper) context).getBaseContext());
    } else {
      return null;
    }
  }
context

有这种情形,比如AppCompatTextView中的context是被TintContextWrapper包裹进去的,如果此通过getContext()获取的就不是Activity,所以需要检查是否是ContextWrapper,如果是就可以通过getBaseContext()获取包裹的context,再次验证是否是Activity

 public AppCompatTextView(@NonNull Context context) {
        this(context, null);
    }

    public AppCompatTextView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, android.R.attr.textViewStyle);
    }

    public AppCompatTextView(
            @NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(TintContextWrapper.wrap(context), attrs, defStyleAttr);

        ThemeUtils.checkAppCompatTheme(this, getContext());

        mBackgroundTintHelper = new AppCompatBackgroundHelper(this);
        mBackgroundTintHelper.loadFromAttributes(attrs, defStyleAttr);

        mTextHelper = new AppCompatTextHelper(this);
        mTextHelper.loadFromAttributes(attrs, defStyleAttr);
        mTextHelper.applyCompoundDrawablesTints();

        mTextClassifierHelper = new AppCompatTextClassifierHelper(this);
    }

相关文章

网友评论

      本文标题:从 context 获取Activity

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