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方法加载的系统控件都会被替换

转载于:https://juejin.im/post/5cadeacc6fb9a068b16e09a2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值