LayoutInflater的Factory和Factory2有什么区别?

11

在Android SDK中有两个公共接口:
LayoutInflater.FactoryLayoutInflater.Factory2,但官方文档对这些接口没有提供有用的信息,甚至包括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,我应该使用哪个工厂?它们之间有什么区别?


2个回答

5

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

用法 -
当您需要为创建的新视图设置特定的父级时,请使用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只是带有View parent选项的Factory的重载。

3

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

如果您需要提供视图创建后要放置的父级,则应使用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);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接