1. 概述
上篇文章我们分析了 LayoutInflater.from(this).inflate()方法的源码,我们可以知道:只要设置 setFactory(),那么就可以实现自己 自己想要实现的一套逻辑,如果不是很清楚 LayoutInflater.from(this).inflate()源码的,可以先去看下我的这篇文章
这篇文章主要分析了怎样可以拦截View的创建,其实很简单,就是直接利用系统的源码设置一个Factory即可,下边就来看具体如何实现。
2. 具体使用
1>:基类BaseSkinActivity代码如下,意思就是只要BaseSkinActivity的子类的布局文件中如果有Button控件,就把它设置为TextView,并且把文字内容设置为 拦截:
/**
* Email: 2185134304@qq.com
* Created by JackChen 2018/4/15 12:02
* Version 1.0
* Params:
* Description: 插件换肤的基类
*/
public abstract class BaseSkinActivity extends BaseActivity {
// 后面会写插件换肤 预留的东西
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
LayoutInflater layoutInflater = LayoutInflater.from(this);
LayoutInflaterCompat.setFactory(layoutInflater, new LayoutInflaterFactory() {
@Override
public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
// 拦截到View的创建
Log.e("TAG","拦截到View的创建");
if(name.equals("Button")){
TextView tv = new TextView(BaseSkinActivity.this);
tv.setText("拦截");
return tv;
}
return null;
}
});
super.onCreate(savedInstanceState);
}
}
2>:activity_main布局文件如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="cn.novate.essayjoke_day01.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/test_btn"
android:text="换肤"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/test_iv"
android:src="@drawable/image_src"
android:layout_marginTop="10dp"
/>
</LinearLayout>
3. 效果如下
设置setFactory之前,activity_main上边是一个Button:
图片.png
设置setFactory之后,之前的Button变为 TextView,并且设置文字为 拦截:
图片.png