Search code examples
javaandroidlayout-inflater

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


There is two public interfaces:
LayoutInflater.Factory and LayoutInflater.Factory2 in android sdk, but official documentation can't say something helpfull about this interfaces, even LayoutInflater documentation.

From sources I've understood that if Factory2 was set then it will be used and Factory otherwise:

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() also have very laconic documentation:

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


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


Solution

  • The only difference is that in Factory2 you can configure who's the new view's parent view will be.

    Usage -
    Use Factory2 when you need to set specific parent to the new view your creating.(Support API 11 and above only)

    Code - LayoutInflater source:(after removing irrelevant code)

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

    Now 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);
        }
    

    Now you can see that Factory2 is just overload of Factory with the View parent option.