LayoutInflater Factory使用基础与进阶

问题背景

在开发新版本中,遇到一个问题是需要把所有的TextView与继承TextView的View替换为自定义TextView,这个改动对我们项目来说工作量是巨大的。那么有没有好办法呢?

想想在使用android support library时,view有些属性本来是不支持的,突然就支持了而且能向下兼容。那是怎么实现的呢?其实就是使用LayoutInflater Factory,将XXXView替换为了AppCompactXXXView,这正是我们想要的。接下来我们就来介绍一下:

LayoutInflater Factory 是什么?

说到LayoutInflater大家肯定都不会陌生,今天我们主要介绍以下两个方法:

  • setFactory(LayoutInflater.Factory factory)
  • setFactory2(LayoutInflater.Factory2 factory)

setFactory2是在SDK>11时候添加的,如果你是基于11以上的就使用setFactory2,否则就使用setFactory ,两者功能基本一致。当然你不想考虑兼容问题可以直接使用LayoutInflaterCompat.setFactory()。让我们看看这两个方法:

public interface Factory {
  public View onCreateView(String name, Context context, AttributeSet attrs);
  }
public interface Factory2 extends Factory {
  public View onCreateView(View parent, String name, Context context, AttributeSet attrs);
  }

其实就是一个接口,在系统填充view前会回调该接口,你可以去自定义布局的填充(有点类似于拦截器)。

LayoutInflater Factory 有什么用?

使用LayoutInflater Factory的这一特性可以做很多事:

  • 提高view构建的效率

    • 当我们使用自定义view时,需要在xml中使用完整类名,系统实际就是根据完整类名进行反射构建。我们可以自己new出view避免系统反射调用,提高效率。
  • 替换默认view实现,改变或添加属性

    • 替换系统控件
    • 一键换肤解决方案

LayoutInflater Factory 怎么用?

我们先写个小例子属性一下使用:

public class TestLayoutFactory implements LayoutInflaterFactory {

    private static final String TAG = "TestLayoutFactory";

    @Override
    public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
        Log.d(TAG, "name = " + name);
        int n = attrs.getAttributeCount();
        for (int i = 0; i < n; i++)
        {
            Log.d(TAG, attrs.getAttributeName(i) + " , " + attrs.getAttributeValue(i));
        }

        return null;
    }

}

这里我们继承LayoutInflaterFactory重写了onCreateView(),AttributeSet大家都不陌生,这里的AttributeSet也和自定义view中见到的一样,保存了view的一些属性。代码很简单,就是将view的属性用Log打印出来。

@Override
protected void onCreate(Bundle savedInstanceState) {
    // 注意需在调用super.onCreate(savedInstanceState);之前设置
    LayoutInflaterCompat.setFactory(getLayoutInflater(), new TestLayoutFactory());
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test_layout_factory);
}

在Activity中使用时注意一定要在super.onCreate(savedInstanceState);之前调用。

我们的布局是这样的:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    android:id="@+id/activity_test_layout_factory"
    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"
    tools:context="com.example.licheng.testapp.layoutfactory.TestLayoutFactoryActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/test"
        android:textSize="16sp"
        android:padding="10dp"
        android:textColor="@android:color/white"
        android:background="@android:color/black"
        android:layout_gravity="center"/>

</FrameLayout>

我们看下log:

TestLayoutFactory: name = FrameLayout
TestLayoutFactory: id , @2131427431
TestLayoutFactory: layout_width , -1
TestLayoutFactory: layout_height , -1
TestLayoutFactory: name = TextView
TestLayoutFactory: textSize , 16.0sp
TestLayoutFactory: textColor , @17170443
TestLayoutFactory: layout_gravity , 0x11
TestLayoutFactory: background , @17170444
TestLayoutFactory: padding , 10.0dip
TestLayoutFactory: layout_width , -2
TestLayoutFactory: layout_height , -2
TestLayoutFactory: text , @2131099670

我们发现我们的在xml中给view设置的属性都打印出来了。参数name就是View的名字,我们根据这点就能实现接下来的功能:

提高view构建的效率

我们这里有个自定义的GoTextView,一般使用时如下:

<FrameLayout
    android:id="@+id/activity_test_layout_factory"
    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"
    tools:context="com.example.licheng.testapp.layoutfactory.TestLayoutFactoryActivity">

    <com.example.licheng.testapp.layoutfactory.GoTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/test"
        android:textSize="16sp"
        android:padding="10dp"
        android:textColor="@android:color/white"
        android:background="@android:color/black"
        android:layout_gravity="center"/>

</FrameLayout>

在xml中使用完全类名。我们看下系统是如何构建我们自定义view的,一般的流程:inflate()->createViewFromTag()->CreateView()

我们先看看createViewFromTag()部分重要代码:

if (view == null) {
    final Object lastContext = mConstructorArgs[0];
    mConstructorArgs[0] = context;
    try {
        if (-1 == name.indexOf('.')) {
            view = onCreateView(parent, name, attrs);
        } else {
            view = createView(name, null, attrs);
        }
    } finally {
        mConstructorArgs[0] = lastContext;
    }
}

这里我们可以看到,根据name是否包含“.”来判断是否是自定义view,如果是自定义view就会调用CreateView()

public final View createView(String name, String prefix, AttributeSet attrs)
        throws ClassNotFoundException, InflateException {
    Constructor<? extends View> constructor = sConstructorMap.get(name);
    if (constructor != null && !verifyClassLoader(constructor)) {
        constructor = null;
        sConstructorMap.remove(name);
    }
    Class<? extends View> clazz = null;

    try {
        Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);

        if (constructor == null) {
            // Class not found in the cache, see if it's real, and try to add it
            clazz = mContext.getClassLoader().loadClass(
                    prefix != null ? (prefix + name) : name).asSubclass(View.class);

            if (mFilter != null && clazz != null) {
                boolean allowed = mFilter.onLoadClass(clazz);
                if (!allowed) {
                    failNotAllowed(name, prefix, attrs);
                }
            }
            constructor = clazz.getConstructor(mConstructorSignature);
            constructor.setAccessible(true);
            sConstructorMap.put(name, constructor);
        } else {
            // If we have a filter, apply it to cached constructor
            if (mFilter != null) {
                // Have we seen this name before?
                Boolean allowedState = mFilterMap.get(name);
                if (allowedState == null) {
                    // New class -- remember whether it is allowed
                    clazz = mContext.getClassLoader().loadClass(
                            prefix != null ? (prefix + name) : name).asSubclass(View.class);

                    boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
                    mFilterMap.put(name, allowed);
                    if (!allowed) {
                        failNotAllowed(name, prefix, attrs);
                    }
                } else if (allowedState.equals(Boolean.FALSE)) {
                    failNotAllowed(name, prefix, attrs);
                }
            }
        }

        Object[] args = mConstructorArgs;
        args[1] = attrs;

        final View view = constructor.newInstance(args);
        if (view instanceof ViewStub) {
            // Use the same context when inflating ViewStub later.
            final ViewStub viewStub = (ViewStub) view;
            viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
        }
        return view;

    } catch (NoSuchMethodException e) {
        // 省略代码...
    }
}

我们根据以上代码可以知道系统根据标签name反射构建我们的自定义view,我们使用LayoutInflater Factory就可以自己去构建view :

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    android:id="@+id/activity_test_layout_factory"
    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"
    tools:context="com.example.licheng.testapp.layoutfactory.TestLayoutFactoryActivity">

    <GoTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/test"
        android:textSize="16sp"
        android:padding="10dp"
        android:textColor="@android:color/white"
        android:background="@android:color/black"
        android:layout_gravity="center"/>

</FrameLayout>
public class TestLayoutFactory implements LayoutInflaterFactory {

    private static final String TAG = "TestLayoutFactory";

    @Override
    public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {

        if (TextUtils.equals("GoTextView", name)) {
            return new GoTextView(context,attrs);
        }

        return null;
    }

}

我们可以不用在xml中写完整的类名,只要匹配到name我们就可以直接new出自定义view,避免系统反射调用,提高view创建速度。

替换默认View的实现

回到我们最初的需求,就是将系统TextView全部替换为自定义的GoTextView,从上面的例子我们就知道该怎么做了:

我们项目中一般都有一个BaseActivity,我们在其中setFactory

public class BaseActivity extends AppCompatActivity {

    private static final String TAG = "BaseActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 注意需在调用super.onCreate(savedInstanceState);之前设置
        LayoutInflaterCompat.setFactory(getLayoutInflater(), new TestLayoutFactory());
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_layout_factory);
    }
}

然后再实现onCreateView(),就这么简单的实现了“狸猫换太子”。

@Override
public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {

    if (TextUtils.equals("TextView", name)) {
        return new GoTextView(context,attrs);
    }

    return null;
}

其实兼容包也是这么做的,我们可以点开support library 的AppCompatActivity

protected void onCreate(@Nullable Bundle savedInstanceState) {
    final AppCompatDelegate delegate = getDelegate();
    delegate.installViewFactory();
    delegate.onCreate(savedInstanceState);
    // 省略代码....
    super.onCreate(savedInstanceState);
}

AppCompatActivity大部分功能是交给AppCompatDelegate去实现的,在onCreate中我们可以看到是调用了installViewFactory()

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

其实就是设置了一个Factory,我们看下设置的Factory的具体实现:

public 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 = new AppCompatTextView(context, attrs);
            break;
        case "ImageView":
            view = new AppCompatImageView(context, attrs);
            break;
        case "Button":
            view = new AppCompatButton(context, attrs);
            break;
        case "EditText":
            view = new AppCompatEditText(context, attrs);
            break;
        case "Spinner":
            view = new AppCompatSpinner(context, attrs);
            break;
        case "ImageButton":
            view = new AppCompatImageButton(context, attrs);
            break;
        case "CheckBox":
            view = new AppCompatCheckBox(context, attrs);
            break;
        case "RadioButton":
            view = new AppCompatRadioButton(context, attrs);
            break;
        case "CheckedTextView":
            view = new AppCompatCheckedTextView(context, attrs);
            break;
        case "AutoCompleteTextView":
            view = new AppCompatAutoCompleteTextView(context, attrs);
            break;
        case "MultiAutoCompleteTextView":
            view = new AppCompatMultiAutoCompleteTextView(context, attrs);
            break;
        case "RatingBar":
            view = new AppCompatRatingBar(context, attrs);
            break;
        case "SeekBar":
            view = new AppCompatSeekBar(context, attrs);
            break;
    }

    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 it's android:onClick
        checkOnClickListener(view, attrs);
    }

    return view;
}

从代码中可以一目了然的看出来,所有继承AppCompactActivity的Activity中都会将系统的 xxxView 替换为support library中的 AppCompatxxx,这就实现了新增功能与向下兼容。

LayoutInflater Factory 使用中遇到的问题

LayoutInflater Factoty有一个限制,只能被设置一次。如果被多次设置会抛出异常

/**
 * Attach a custom Factory interface for creating views while using
 * this LayoutInflater. This must not be null, and can only be set once;
 * after setting, you can not change the factory.
 *
 * @see LayoutInflater#setFactory(android.view.LayoutInflater.Factory)
 */
public static void setFactory(LayoutInflater inflater, LayoutInflaterFactory factory) {
    IMPL.setFactory(inflater, factory);
}

这个限制就会导致一个问题,我们在继承AppCompactActivity后设置自己的Factory会导致AppCompactActivity的Factory无效,无法使用最新的特性,那该怎么办的呢?

有以下几种解决方案:

  • 在Activity的onCreateView()回调中实现我们自己的逻辑
  • 使用layoutInflater.cloneInContext(context);克隆一个layoutInflater,再在这个克隆的里面setFactory
  • 在我们的Factory中先调用AppCompatDelegate的createView()在进行我们的逻辑

我们来分别介绍一下:

在Activity的onCreateView()回调中实现我们自己的逻辑

Activity其实已经实现了Factory接口,并把实现通过接口回调的方式交给用户自己去做了,所以我们只需重载onCreateView()

我们看AppCompatDelegate中的代码,会先调用Activity的OnCreateView,如果返回不为null则自己进行构建。

/**
 * From {@link android.support.v4.view.LayoutInflaterFactory}
 */
@Override
public final View onCreateView(View parent, String name,
        Context context, AttributeSet attrs) {
    // First let the Activity's Factory try and inflate the view
    final View view = callActivityOnCreateView(parent, name, context, attrs);
    if (view != null) {
        return view;
    }

    // If the Factory didn't handle it, let our createView() method try
    return createView(parent, name, context, attrs);
}

所以我们可以在Activity的onCreateView中进行“拦截”,Activity的代码就是重载onCreateView:

public class TestLayoutFactoryActivity extends AppCompatActivity {

    private static final String TAG = "TestLayoutFactoryActivi";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 注意需在调用super.onCreate(savedInstanceState);之前设置
        //LayoutInflaterCompat.setFactory(getLayoutInflater(), new TestLayoutFactory());
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_layout_factory);
    }

    @Override
    public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
        if (TextUtils.equals("TextView", name)) {
            return new GoTextView(context, attrs);
        }
        // return null 交给系统去构建view
        return null;
    }
}

使用layoutInflater.cloneInContext(context);

layoutInflater提供api是cloneInContext(context);可以克隆一个layoutInflater

LayoutInflater newLayoutInlflater = getLayoutInflater().cloneInContext(context);
LayoutInflaterCompat.setFactory(newLayoutInlflater,new TestLayoutFactory());

这种方式不是很方便,需要在使用中将默认的LayoutInflater替换为我们新的LayoutInflater,但是也是一种思路。

在Factory中先调用AppCompatDelegate的createView()

好在AppCompatDelegate的createView()是public的,所以我们可以先执行自己的逻辑再交给delegate去实现:

public class TestLayoutFactory implements LayoutInflaterFactory {

    private AppCompatDelegate appCompatDelegate;

    private static final String TAG = "TestLayoutFactory";

    public TestLayoutFactory(AppCompatDelegate appCompatDelegate) {
        this.appCompatDelegate = appCompatDelegate;
    }

    @Override
    public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
        View result = null;

        // 实现我们自己的逻辑
        if (TextUtils.equals("TextView", name)) {
            result =  new GoTextView(context,attrs);
        }

        if (result == null) {
            // 使用 AppCompat 获取view
            result = appCompatDelegate.createView(parent, name, context, attrs);
        }
        return result;
    }

}

总结

LayoutInflater Factory这一特性很强大,能做的远不止上面那些事。比如大部分“一键换肤”都是使用了这一特性来实现的。

参考

http://blog.bradcampbell.nz/layoutinflater-factories/
http://willowtreeapps.com/blog/app-development-how-to-get-the-right-layoutinflater/
http://blog.csdn.net/lmj623565791/article/details/51503977

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值