LayoutInflater的Factory和Factory2有什么区别

What's the difference between LayoutInflater's Factory and Factory2

有两个public接口:
LayoutInflater.Factory and LayoutInflater.Factory2 in android sdk, but official documentation can't say something helpfull about this interfaces, even LayoutInflater 文档。

据我了解,如果设置了 Factory2,则将使用它,否则将使用 Factory

View view;
if (mFactory2 != null) {
    view = mFactory2.onCreateView(parent, name, context, attrs);
} else if (mFactory != null) {
    view = mFactory.onCreateView(name, context, attrs);
} else {
    view = null;
}

setFactory2() 也有非常简洁的文档:

/**
 * Like {@link #setFactory}, but allows you to set a {@link Factory2}
 * interface.
 */
public void setFactory2(Factory2 factory) {


如果我想将自定义工厂设置为 LayoutInflater,我应该使用哪个工厂? 它们有什么区别?

唯一的区别是,在 Factory2 中,您可以配置新视图的 parent view 是谁。

用法-
当您需要将特定父级设置为您的新视图时,请使用 Factory2 创建。(仅支持 API 11 及以上)

代码 - LayoutInflater 来源:(删除无关代码后)

public interface Factory {
         // @return View Newly created view. 
        public View onCreateView(String name, Context context, AttributeSet attrs);
    }

现在Factory2:

public interface Factory2 extends Factory {
         // @param parent The parent that the created view will be placed in.
         // @return View Newly created view. 
        public View onCreateView(View parent, String name, Context context, AttributeSet attrs);
    }

现在您可以看到 Factory2 只是 FactoryView parent 选项的重载。

Which factory should I use If I want to set custom factory to LayoutInflater? And what is the difference of them?

如果您需要提供创建的视图将放置在其中的父视图,您需要使用 Factory2。但如果您的目标 API 级别 11+,通常使用 Factory2。否则,只需使用 Factory.

这里是Factory

class MyLayoutInflaterFactory implements LayoutInflater.Factory {

    @Override
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        if (TextUtils.equals(name, "MyCustomLayout")) {
            return new MyCustomLayout(context, attrs);
        }
        // and so on...
        return super.onCreateView(name, context attrs);
    }
}

这里是Factory2

class MyLayoutInflaterFactory2 implements LayoutInflater.Factory2 {

    @Override
    public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
        if (TextUtils.equals(name, "MyCustomLayout")) {
            return new MyCustomLayout(context, attrs);
        }
        // and so on...
        return super.onCreateView(parent, name, context, attrs);
    }
}