AppCompatActivity怎么对View做的拦截

1.AppCompatActivity对View偷偷做的替换

布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity"
    android:paddingLeft="20dp">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:layout_marginTop="20dp"/>

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:src="@mipmap/ic_launcher"
        android:layout_marginTop="20dp"/>
</LinearLayout>

MainActivity的java代码

public class MainActivity extends AppCompatActivity {
    @ViewById(R.id.textView)
    TextView mTextView;
    @ViewById(R.id.imageView)
    ImageView mImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ViewUtils.inject(this);
        System.out.println("==============================");
        System.out.println(mTextView);
        System.out.println(mImageView);
    }
}

运行的结果

2019-04-16 14:58:04.708 15885-15885/? I/System.out: ==============================
2019-04-16 14:58:04.709 15885-15885/? I/System.out: android.support.v7.widget.AppCompatTextView{c63b90 V.ED..C.. ......ID 0,0-0,0 #7f0800a8 app:id/textView}
2019-04-16 14:58:04.709 15885-15885/? I/System.out: android.support.v7.widget.AppCompatImageView{bed6c89 V.ED..... ......ID 0,0-0,0 #7f080054 app:id/imageView}

TextViewImageView被偷偷替换成了AppCompatTextView和AppCompatImageView

2.AppCompatActivity中onCreate方法

protected void onCreate(@Nullable Bundle savedInstanceState) {
        final AppCompatDelegate delegate = getDelegate();
        delegate.installViewFactory();
        delegate.onCreate(savedInstanceState);
        if (delegate.applyDayNight() && mThemeId != 0) {
            // If DayNight has been applied, we need to re-apply the theme for
            // the changes to take effect. On API 23+, we should bypass
            // setTheme(), which will no-op if the theme ID is identical to the
            // current theme ID.
            if (Build.VERSION.SDK_INT >= 23) {
                onApplyThemeResource(getTheme(), mThemeId, false);
            } else {
                setTheme(mThemeId);
            }
        }
        super.onCreate(savedInstanceState);
}

看看delegate是什么

private static AppCompatDelegate create(Context context, Window window,
            AppCompatCallback callback) {
        if (Build.VERSION.SDK_INT >= 24) {
            return new AppCompatDelegateImplN(context, window, callback);
        } else if (Build.VERSION.SDK_INT >= 23) {
            return new AppCompatDelegateImplV23(context, window, callback);
        } else {
            return new AppCompatDelegateImplV14(context, window, callback);
        }
}

由于AppCompatDelegateImplN extends AppCompatDelegateImplV23
AppCompatDelegateImplV23 extends AppCompatDelegateImplV14
AppCompatDelegateImplV14 extends AppCompatDelegateImplV9
直接看AppCompatDelegateImplV9中的installViewFactory方法

 public void installViewFactory() {
        LayoutInflater layoutInflater = LayoutInflater.from(mContext);
        if (layoutInflater.getFactory() == null) {
            LayoutInflaterCompat.setFactory2(layoutInflater, this);
        } else {
            if (!(layoutInflater.getFactory2() instanceof AppCompatDelegateImplV9)) {
                Log.i(TAG, "The Activity's LayoutInflater already has a Factory installed"
                        + " so we can not install AppCompat's");
            }
        }
 }

LayoutInflaterCompat.setFactory2方法.

public static void setFactory2(
            @NonNull LayoutInflater inflater, @NonNull LayoutInflater.Factory2 factory) {
        IMPL.setFactory2(inflater, factory);
}
public void setFactory2(LayoutInflater inflater, LayoutInflater.Factory2 factory) {
           inflater.setFactory2(factory);

           final LayoutInflater.Factory f = inflater.getFactory();
           if (f instanceof LayoutInflater.Factory2) {
               // The merged factory is now set to getFactory(), but not getFactory2() (pre-v21).
               // We will now try and force set the merged factory to mFactory2
               forceSetFactory2(inflater, (LayoutInflater.Factory2) f);
           } else {
               // Else, we will force set the original wrapped Factory2
               forceSetFactory2(inflater, factory);
           }
       }

很明显,给inflater设置了factory。根据LayoutInflater创建View这篇博文,设置factory后会回调createView方法,在此方法中做View创建等等拦截

public View createView(View parent, final String name, @NonNull Context context,
            @NonNull AttributeSet attrs) {
        if (mAppCompatViewInflater == null) {
            TypedArray a = mContext.obtainStyledAttributes(R.styleable.AppCompatTheme);
            String viewInflaterClassName =
                    a.getString(R.styleable.AppCompatTheme_viewInflaterClass);
            if ((viewInflaterClassName == null)
                    || AppCompatViewInflater.class.getName().equals(viewInflaterClassName)) {
                // Either default class name or set explicitly to null. In both cases
                // create the base inflater (no reflection)
                mAppCompatViewInflater = new AppCompatViewInflater();
            } else {
                try {
                    Class viewInflaterClass = Class.forName(viewInflaterClassName);
                    mAppCompatViewInflater =
                            (AppCompatViewInflater) viewInflaterClass.getDeclaredConstructor()
                                    .newInstance();
                } catch (Throwable t) {
                    Log.i(TAG, "Failed to instantiate custom view inflater "
                            + viewInflaterClassName + ". Falling back to default.", t);
                    mAppCompatViewInflater = new AppCompatViewInflater();
                }
            }
        }

        boolean inheritContext = false;
        if (IS_PRE_LOLLIPOP) {
            inheritContext = (attrs instanceof XmlPullParser)
                    // If we have a XmlPullParser, we can detect where we are in the layout
                    ? ((XmlPullParser) attrs).getDepth() > 1
                    // Otherwise we have to use the old heuristic
                    : shouldInheritContext((ViewParent) parent);
        }

        return mAppCompatViewInflater.createView(parent, name, context, attrs, inheritContext,
                IS_PRE_LOLLIPOP, /* Only read android:theme pre-L (L+ handles this anyway) */
                true, /* Read read app:theme as a fallback at all times for legacy reasons */
                VectorEnabledTintResources.shouldBeUsed() /* Only tint wrap the context if enabled */
        );
    }

mAppCompatViewInflater.createView方法

final View createView(View parent, final String name, @NonNull Context context,
           @NonNull AttributeSet attrs, boolean inheritContext,
           boolean readAndroidTheme, boolean readAppTheme, boolean wrapContext) {
       final Context originalContext = context;

       // We can emulate Lollipop's android:theme attribute propagating down the view hierarchy
       // by using the parent's context
       if (inheritContext && parent != null) {
           context = parent.getContext();
       }
       if (readAndroidTheme || readAppTheme) {
           // We then apply the theme on the context, if specified
           context = themifyContext(context, attrs, readAndroidTheme, readAppTheme);
       }
       if (wrapContext) {
           context = TintContextWrapper.wrap(context);
       }

       View view = null;

       // We need to 'inject' our tint aware Views in place of the standard framework versions
       switch (name) {
           case "TextView":
               view = createTextView(context, attrs);
               verifyNotNull(view, name);
               break;
           case "ImageView":
               view = createImageView(context, attrs);
               verifyNotNull(view, name);
               break;
           case "Button":
               view = createButton(context, attrs);
               verifyNotNull(view, name);
               break;
           case "EditText":
               view = createEditText(context, attrs);
               verifyNotNull(view, name);
               break;
           case "Spinner":
               view = createSpinner(context, attrs);
               verifyNotNull(view, name);
               break;
           case "ImageButton":
               view = createImageButton(context, attrs);
               verifyNotNull(view, name);
               break;
           case "CheckBox":
               view = createCheckBox(context, attrs);
               verifyNotNull(view, name);
               break;
           case "RadioButton":
               view = createRadioButton(context, attrs);
               verifyNotNull(view, name);
               break;
           case "CheckedTextView":
               view = createCheckedTextView(context, attrs);
               verifyNotNull(view, name);
               break;
           case "AutoCompleteTextView":
               view = createAutoCompleteTextView(context, attrs);
               verifyNotNull(view, name);
               break;
           case "MultiAutoCompleteTextView":
               view = createMultiAutoCompleteTextView(context, attrs);
               verifyNotNull(view, name);
               break;
           case "RatingBar":
               view = createRatingBar(context, attrs);
               verifyNotNull(view, name);
               break;
           case "SeekBar":
               view = createSeekBar(context, attrs);
               verifyNotNull(view, name);
               break;
           default:
               // The fallback that allows extending class to take over view inflation
               // for other tags. Note that we don't check that the result is not-null.
               // That allows the custom inflater path to fall back on the default one
               // later in this method.
               view = createView(context, name, attrs);
       }

       if (view == null && originalContext != context) {
           // If the original context does not equal our themed context, then we need to manually
           // inflate it using the name so that android:theme takes effect.
           view = createViewFromTag(context, name, attrs);
       }

       if (view != null) {
           // If we have created a view, check its android:onClick
           checkOnClickListener(view, attrs);
       }

       return view;
   }

这里对创建的View时做了拦截

3.总结

我们的页面继承普通的Activity时没有设置factory,而AppCompatActivity设置了factory。所以AppCompatActivitysetContentView方法加载的系统控件都会被替换

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 196,302评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,563评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,433评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,628评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,467评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,354评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,777评论 3 387
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,419评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,725评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,768评论 2 314
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,543评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,387评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,794评论 3 300
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,032评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,305评论 1 252
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,741评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,946评论 2 336

推荐阅读更多精彩内容