【问题标题】:What's the difference between LayoutInflater's Factory and Factory2LayoutInflater Factory 和 Factory 2 有什么区别
【发布时间】:2017-01-08 05:52:34
【问题描述】:

有两个公共接口:
LayoutInflater.FactoryLayoutInflater.Factory2 在 android sdk 中,但官方文档不能说有关此接口的有用信息,即使是 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,我应该使用哪个工厂? 它们有什么区别?

【问题讨论】:

    标签: java android layout-inflater


    【解决方案1】:

    唯一的区别是,在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 只是带​​有 View parent 选项的 Factory 的重载。

    【讨论】:

      【解决方案2】:

      如果我想设置自定义工厂,我应该使用哪个工厂 布局充气机?它们有什么区别?

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

      【讨论】:

        猜你喜欢
        • 2013-09-17
        • 2011-11-12
        • 1970-01-01
        • 2017-10-01
        • 2013-07-22
        • 1970-01-01
        • 1970-01-01
        • 2021-09-03
        • 1970-01-01
        相关资源
        最近更新 更多