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?
Put simply, an inflater allows you to create a View from a resource layout file so that you do not need to create everything programmatically. In your example, you inflate the layout R. layout.
Use getLayoutInflater() to get the LayoutInflater instead of calling LayoutInflater. from(Context).
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.
Which factory should I use If I want to set custom factory to LayoutInflater? And what is the difference of them?
If you need to supply the parent that the view created will be placed in, you want to use Factory2
. But generally use Factory2
if your targeting API level 11+. Otherwise, just use Factory
.
Here is 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);
}
}
Here is 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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With